【发布时间】:2021-05-21 15:45:51
【问题描述】:
在 6 行 4 列的矩阵 A 中。
其中'#' = blocked path 和'.' = allowed path..
A = [[. . . #],
[# . # #],
[# . # .],
[# . . .],
[# . . .],
[# . . .]
]
如何找到从左上角到左下角所需的步数。我能够从左上角到右下角遍历矩阵,但找不到steps(which is 8 here).。但是下面的代码我得到了答案12 是错误的
我的代码如下:
private static int numSteps(char[][] A) {
int row = A.length;
int col = A[0].length;
// directions array for row and column
// for north, south, east , west
int r[] = {-1, 1, 0, 0};
int c[] = {0, 0, 1, -1};
int steps = 0;
LinkedList<String> queuePos = new LinkedList<String>();
queuePos.add("0,0");
boolean[][] visited = new boolean[row][col];
while(!queuePos.isEmpty()) {
String pos = queuePos.poll();
int rowPos = Integer.parseInt(pos.split(",")[0]);
int colPos = Integer.parseInt(pos.split(",")[1]);
if(rowPos >= row - 1 && colPos>= col -1) {
return steps;
}
// looping for the four directions for surrounding nodes/neighbours
for(int i=0; i<r.length; i++) {
int newRow = rowPos + r[i];
int newCol = colPos + c[i];
if(newRow < 0 || newCol < 0 || newRow >= row || newCol >= col || A[newRow][newCol] == '#' || visited[newRow][newCol]) {
continue;
}
visited[newRow][newCol] = true;
queuePos.add(newRow + "," + newCol);
if(newRow == row - 1 && newCol == col -1) {
return steps;
}
}
steps+=1;
}
return steps;
}
我不知道应该在哪里将 "steps" 变量增加 1..有人可以在这里提出更正建议吗?
【问题讨论】:
标签: java depth-first-search breadth-first-search path-finding