如何解决查找矩阵中从左上角到右下角遍历所需的步数
在矩阵 A 中,有 6 行和 4 列。
其中 '#' = 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};
int c[] = {0,-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..有人可以在这里提出更正建议吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。