201604-4 遊戲

題目看下來覺得果斷用bfs啊,危險的時間段用一個三維數組來存儲就可以了。

按照這個思路編下來,發現結果不對。仔細看題目給的例子,發現訪問過的點可以多次訪問,就果斷把visited數組的判斷去掉,提交之後發現得了二十分,運行超時,用腳趾頭想想也覺得會超時啊?。

搜了其他人的思路,真真的神仙思路,把visited也存成三維,同一時間段同一點不能多次訪問。我就不明白了,怎麼會有這麼機智的人,果然我是人工智障麼

另:還有要注意下標從1開始。

奉上java滿分代碼

import java.util.*;

public class Main{
    private static int rows, cols;
    private static boolean[][][] visited;

    static class Node{
        public int x;
        public int y;
        public int t;

        public Node(int x, int y, int t) {
            this.x = x;
            this.y = y;
            this.t = t;
        }
    }

    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String[] firstLine = scanner.nextLine().split(" ");
        rows = Integer.parseInt(firstLine[0]);
        cols = Integer.parseInt(firstLine[1]);
        visited = new boolean[10000][rows + 1][cols + 1];
        for(int i = 0; i < Integer.parseInt(firstLine[2]); i++){
            String[] line = scanner.nextLine().split(" ");
            int r = Integer.parseInt(line[0]);
            int c = Integer.parseInt(line[1]);
            int a = Integer.parseInt(line[2]);
            int b = Integer.parseInt(line[3]);
            for(int t = a; t <= b; t++){
                visited[t][r][c] = true;
            }
        }
        scanner.close();

        System.out.println(bfs());
    }

    private static int bfs(){
        Node start = new Node(1, 1, 0);
        visited[0][1][1] = true;
        Queue<Node> queue = new LinkedList<>();
        queue.add(start);
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

        while (!queue.isEmpty()){
            Node front = queue.poll();

            if(front.x == rows && front.y == cols)
                return front.t;

            int t = front.t + 1;
            for(int[] dir : dirs){
                int x = front.x + dir[0];
                int y = front.y + dir[1];

                if(x < 1 || x > rows || y < 1 || y > cols)
                    continue;

                if(visited[t][x][y])
                    continue;

                visited[t][x][y] = true;
                queue.add(new Node(x, y, t));
            }
        }

        return 0;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章