题目描述
走迷宫
样例
懒人不想写
算法1
(暴力枚举) $O(n^2)$
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
static Scanner sc = new Scanner(System.in);
static int n = sc.nextInt();
static int m = sc.nextInt();
static int[][] mymap = new int[n][m];//记录地图
static int[][] d = new int[n][m];//记录距离
static Node[][] prev = new Node[n][m];//记录它的上一个节点
static int bfs() {
int[] dx = new int[]{1, -1, 0, 0};
int[] dy = new int[]{0, 0, 1, -1};//记录上下左右移动
Queue<Node> ss = new LinkedList<Node>();//bfs核心队列
ss.offer(new Node(0, 0));
while (!ss.isEmpty()) {
Node a = ss.poll();
for (int i = 0; i < 4; i++) {
int x = dx[i] + a.x;
int y = dy[i] + a.y;
if (x >= 0 && y >= 0 && x < n && y < m && mymap[x][y] == 0 && d[x][y] == 0) {
ss.offer(new Node(x, y));
d[x][y] = d[a.x][a.y] + 1;
prev[x][y] = a;
}
}
}
/*
//打印出走过的路径
int x = n-1;
int y = m-1;
while(!(x==0&&y==0)){
System.out.println(x+” “+y);
x= prev[x][y].x;
y= prev[x][y].y;
}
*/
return d[n - 1][m - 1];
}
public static void main(String[] args) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mymap[i][j] = sc.nextInt();
}
}
System.out.println(bfs());
}
}
时间复杂度
参考文献
C++ 代码
blablabla
```