例外類如下:
static class Point {
public int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(Point a){
this.x=a.x;
this.y=a.y;
}
}
// 無法使用遞回 迷宮問題bfs
// grid 0 可走 1 障礙
// @return 回傳值是pre 代表每個點的前一個點
static int aa,bb;
static int[][] dis = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
static Point[][] map(int[][] grid) {
Queue<Point> q = new LinkedList<>();
q.offer(new Point(0, 0));
int n = grid.length, m = grid[0].length;
Point[][] pre = new Point[n][m];
boolean[][] vis = new boolean[n][m];
while (!q.isEmpty()) {
Point p = q.poll();
vis[p.x][p.y] = true;
if (p.x == n - 1 && p.y == m - 1)
return pre;
for (int i = 0; i < 4; i++) {
int nx = p.x + dis[i][0], ny = p.y + dis[i][1];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny] && grid[nx][ny] == 0) {
pre[nx][ny] = new Point(p.x,p.y);
q.offer(new Point(nx, ny));
}
}
}
return new Point[0][0];
}
case '3':
int aa,bb;
System.out.println("請輸入迷宮的行數:");
int p=sc.nextInt();
System.out.println("請輸入迷宮的列數:");
int q=sc.nextInt();
sc.nextLine();
int[][] grid=new int[p][q];
String row;
for(int i = 0;i < p;i++){
System.out.println("請輸入迷宮的第"+(i+1)+"行(0代表可以走,1代表不可以走,用空格分隔):");
row = sc.nextLine();
String[] y = row.split(" ");
for(int j = 0;j < q;j++){
grid[i][j] = Integer.parseInt(y[j]);
}
}
Point[][] pre = map(grid);
if(Objects.requireNonNull(pre)[p-1][q-1] == null){
System.out.println("迷宮沒有出口");
}else{
grid[p-1][q-1] = 2;
aa = pre[p-1][q-1].x;
bb = pre[p-1][q-1].y;
while(true){
grid[aa][bb] = 2;
aa = pre[aa][bb].x;
bb = pre[aa][bb].y;
if(aa == 0 && bb == 0){
grid[aa][bb] = 2;
break;
}
}
System.out.println(grid);
}
break;
idea報的是 bb = pre[aa][bb].y;這行 Exception in thread "main" java.lang.NullPointerException
uj5u.com熱心網友回復:
debug跟一下代碼就能解決的問題,為什么一定要到網上求助?轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/41400.html
標籤:Java相關
