输入: 5 6 ....S* .**... .*..*. *..**. .T.... 输出: 7 import java.util.*; // 类 记录当前 坐标x y 步数d 的状态 class Node{ public int x; public int y; public int d; public Node(int x, int y, int d) { this.x = x; this.y = y; this.d = d; } } public class LANQIAO1 { public static String[] tmp = new String[110]; public static char[][] maze = new char[110][110]; public static boolean[][] vis = new boolean[110][110]; public static int[][] dir = {{-1,0},{0,-1},{1,0},{0,1}}; public static int n; public static int m; // 起点 public static int bfs(int sx,int sy){ Queue<Node> q = new LinkedList(); // 把当前位置入队 q.offer(new Node(sx ,sy ,0)); // 标记当前位置已被访问 vis[sx][sy] = true; while (!q.isEmpty()){ // 队列不空则出队队首元素并记录队首元素于now中 Node now = q.peek(); q.poll(); // 将当前位置的四个方向可访问元素入队 for (int i = 0; i < 4; i++) { int tx = now.x + dir[i][0]; int ty = now.y + dir[i][1]; // 判断元素是否可以入队 if(in(tx,ty) && maze[tx][ty] != '*' && !vis[tx][ty]){ // 如果找到终点则一层层返回 因为是now的下一层所以返回d+1(比放到最前面少调用一次) if(maze[tx][ty] == 'T'){ return now.d + 1; }else { // 没找到终点则新元素入队 vis[tx][ty] = true; q.offer(new Node(tx,ty,now.d + 1)); } } } } // 遍历完所有可访问位置且没有找到T返回 return -1; } public static boolean in(int x,int y){ return x >= 0 && x < n && y >= 0 && y <m; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); for (int i = 0; i < n; i++) { tmp[i] = sc.next(); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { maze[i][j] = tmp[i].charAt(j); } } int x = 0,y = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if(maze[i][j] == 'S'){ x = i;y = j; } } } System.out.println(bfs(x, y)); } }
bfs广度优先搜索-迷宫问题最优解
最新推荐文章于 2024-09-30 10:36:33 发布