题目看下来觉得果断用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;
}
}