主要思想与走迷宫相差不大,就是嗅探四周,若可行就入队,直到队空结束
要求多长时间实际上就是求最远的点离原点有多远
所求点结构,step为离起始点距离
public class Node{
int x;
int y;
int step;
public Node(){}
public Node(int x,int y,int step){
this.x = x;
this.y = y;
this.step = step;
}
}
具体执行代码
public int BFS(char[][] MAT,int N,int row,int col){
//新建一个图判断走过的路
boolean[][] map = new boolean[N][N];
//初始化 可以燃烧为T否则为F
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map.length; j++) {
if (MAT[i][j] == 'G') {
map[i][j] = true;
}else {
map[i][j] = false;
}
}
}
Queue<Node> nodes = new LinkedList<>();
nodes.add(new Node(row,col,0));
while(!nodes.isEmpty()){
Node tempNode = nodes.poll();
int x = tempNode.x;
int y = tempNode.y;
int step = tempNode.step;
//已走
map[x][y] = false;
//嗅探四周
if (x+1 < N && map[x+1][y] == true ) {
nodes.add(new Node(x+1,y,step+1));
}
if (x-1 >= 0 && map[x-1][y] == true) {
nodes.add(new Node(x-1,y,step+1));
}
if (y+1 < N && map[x][y+1] == true) {
nodes.add(new Node(x,y+1,step+1));
}
if (y-1 >= 0 && map[x][y-1] == true) {
nodes.add(new Node(x,y-1,step+1));
}
if (nodes.isEmpty()) {
return tempNode.step;
}
}
return -1;
}