Algorithm for finding all paths in a NxN grid

前端 未结 10 1434
忘了有多久
忘了有多久 2020-11-28 08:27

Imagine a robot sitting on the upper left hand corner of an NxN grid. The robot can only move in two directions: right and down. How many possible paths are there for the ro

10条回答
  •  悲&欢浪女
    2020-11-28 08:54

    Below is the code in Java to count all the possible paths from top left corner to bottom right corner of a NXN matrix.

    public class paths_in_matrix {
    
        /**
         * @param args
         */
        static int n=5;
        private boolean[][] board=new boolean[n][n];
        int numPaths=0;
        paths_in_matrix(){
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    board[i][j]=false;
                }
            }
        }
        private void togglePiece(int i,int j){
            this.board[i][j]=!this.board[i][j];
        }
        private boolean hasBeenVisited(int i,int j){
            return this.board[i][j];
        }
        private boolean exists(int i,int j){
            return i < n && i > -1 && j < n && j > -1;
        }
        private boolean viablePosition(int i,int j){
            return exists(i, j) && !hasBeenVisited(i,j);
        }
        private void traversePaths(int i,int j){
            //BASE CASE: if reached (n - 1, n - 1), count as path and stop. 
            if (i == (n - 1) && j == (n - 1)) {
              this.numPaths++;
              return;
            }
            this.togglePiece(i, j);
            //RECURSIVE CASE: if next point is a viable position, go there and make the same decision
    
            //go right if possible
            if (this.viablePosition(i, j + 1)) {
              traversePaths(i, j + 1);
            }
          //go left if possible
            if (this.viablePosition(i, j - 1)) {
              traversePaths( i, j - 1);
            }
    
            //go down if possible
            if (this.viablePosition(i + 1, j)) {
              traversePaths( i + 1, j);
            }
    
            //go up if possible
            if (this.viablePosition(i - 1, j)) {
              traversePaths(i - 1, j);
            }
    
            //reset the board back to the way you found it after you've gone forward so that other paths can see it as a viable position for their routes
            this.togglePiece(i, j);
    
        }
        private int robotPaths(){
    
            traversePaths(0,0);
            return this.numPaths;
        }
        public static void main(String[] args) {
            paths_in_matrix mat=new paths_in_matrix();
            System.out.println(mat.robotPaths());
        }
    
    }
    

提交回复
热议问题