图的BFS----迷宫问题

题目描述:

...11111111111111111111111111111
11.111111........1111111111.1111
11.111111..111.11111111.....1111
11.11111111111.1111111111.111111
11.111111.................111111
11.111111.11111111111.11111.1111
11.111111.11111111111.11111..111
11..........111111111.11111.1111
11111.111111111111111.11....1111
11111.111111111111111.11.11.1111
11111.111111111111111.11.11.1111
111...111111111111111.11.11.1111
111.11111111111111111....11.1111
111.11111111111111111111111.1111
111.1111.111111111111111......11
111.1111.......111111111.1111.11
111.1111.11111.111111111.1111.11
111......11111.111111111.1111111
11111111111111.111111111.111...1
11111111111111...............1.1
111111111111111111111111111111..

如上图的迷宫,入口,出口分别:左上角,右下角
"1"是墙壁,"."是通路
求最短需要走多少步?

代码实现:

 1 import java.util.LinkedList;
 2 import java.util.Queue;
 3 import java.util.Scanner;
 4 
 5 public class 图的bfs_迷宫 {
 6     public static void main(String[] args) {
 7         Scanner scanner = new Scanner(System.in);
 8         int m = 21;
 9         int n = 32;
10         char[][] graph = new char[m][n];
11         int[][] vis = new int[m][n];// 标记哪些点已经被访问
12         Queue<Node> queue = new LinkedList<>();
13         for (int i = 0; i < m; i++) {
14             graph[i] = scanner.nextLine().toCharArray();
15         }
16         // for (int j = 0; j < graph.length; j++) {
17         // for (int k = 0; k < graph[j].length; k++) {
18         // System.out.print(graph[j][k]);
19         // }
20         // System.out.println();
21         // }
22 
23         Node start = new Node(0, 0, 0);
24         queue.add(start);
25         while (!queue.isEmpty()) {
26             Node poll = queue.poll();
27             int x = poll.x;
28             int y = poll.y;
29             int deep = poll.depth;
30             vis[x][y] = 1;// 标注为已访问
31             // 判断是否到达终点
32             if (x == m - 1 && y == n - 1) {// 走到出口
33                 System.out.println(poll.depth);
34                 break;
35             }
36             // 加四个邻居
37             if (x - 1 >= 0 && vis[x - 1][y] == 0 && graph[x - 1][y] == '.') {
38                 queue.add(new Node(x - 1, y, deep + 1));
39             }
40             if (x + 1 < m && vis[x + 1][y] == 0 && graph[x + 1][y] == '.') {
41                 queue.add(new Node(x + 1, y, deep + 1));
42             }
43             if (y - 1 >= 0 && vis[x][y - 1] == 0 && graph[x][y - 1] == '.') {
44                 queue.add(new Node(x, y - 1, deep + 1));
45             }
46             if (y + 1 < n && vis[x][y + 1] == 0 && graph[x][y + 1] == '.') {
47                 queue.add(new Node(x, y + 1, deep + 1));
48             }
49         }
50     }
51 
52     static class Node {
53         int x;
54         int y;
55         int depth;
56 
57         public Node(int x, int y, int depth) {
58             this.x = x;
59             this.y = y;
60             this.depth = depth;
61         }
62     }
63 }

运行结果:

  

猜你喜欢

转载自www.cnblogs.com/xiaoyh/p/10416114.html