查找矩阵中从左上角到右下角遍历所需的步数

问题描述

在矩阵 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 (将#修改为@)