题目链接:https://www.nowcoder.com/questionTerminal/6276dbbda7094978b0e9ebb183ba37b9
bfs:
import java.util.*;
class Node {
int x;
int y;
int count;
public Node(int x, int y, int count) {
this.x = x;
this.y = y;
this.count = count;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String[] strings = new String[10];
for (int i = 0; i < 10; i++) {
strings[i] = sc.nextLine();
}
System.out.println(bfs(strings,10,10));
}
}
public static int bfs(String[] strings,int m,int n) {
//四个方向
int[][] direct = {{1,0},{0,1},{0,-1},{-1,0}};
//初始节点
Node start = new Node(0,1,0);
//结束节点
Node end = new Node(9,8,0);
//判断是否走过
boolean[][] flag = new boolean[m][n];
Queue<Node> queue = new LinkedList<>();
queue.offer(start);
while (!queue.isEmpty()) {
Node node = queue.poll();
flag[node.x][node.y] = true;
//到达终点
if (node.x == end.x && node.y == end.y) {
return node.count;
}
for (int i = 0; i < 4; i++) {
Node next = new Node(node.x+direct[i][0],node.y+direct[i][1],node.count+1);
if (next.x >= 0 && next.x < m && next.y >= 0 && next.y < n
&& strings[next.x].charAt(next.y) == '.'&& !flag[next.x][next.y]) {
queue.add(next);
}
}
}
return 0;
}
}