Algorithm for finding all paths in a NxN grid

前端 未结 10 1397
忘了有多久
忘了有多久 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:57

    Scenario:
    1. Imagine there is NxN zero indexed matrix.
    2. Initial position of robot is upper-left corner i.e. (N-1, N-1)
    3. Robot wants to reach lower right corner i.e. at (0,0)

    Solution:
    -- In any possible solution robot will move N rights steps and N down steps to reach (0,0), or we can say that initial robot has permission to move N rights steps and N down steps.
    -- When ever robot moves right we reduce its remaining number of right steps by 1, same is for down movement.
    -- At every position(except at boundary, where it will have only one option) robot have two options, one is it can go down or other is it can go right.
    -- It will terminate when robot will have no remaining down of right steps.

    **Below code also have driver method main(), you can change the value of N. N can be >=1

    public class RobotPaths {
    
    public static int robotPaths(int down, int right, String path)
    {
        path = path+ down +","+ right +"  ";
        if(down==0 && right==0)
        {
            System.out.println(path);
            return 1;
        }
    
        int counter = 0;
    
        if(down==0)
            counter = robotPaths(down, right-1, path);
        else if(right==0)
            counter = robotPaths(down-1, right, path);
        else
            counter = robotPaths(down, right-1, path) + robotPaths(down-1, right, path);
    
        return counter;
    }
    
    public static void main(String[] args) 
    {
        int N = 1;
        System.out.println("Total possible paths: "+RobotPaths.robotPaths(N-1, N-1, ""));
    
    }
    

    }

提交回复
热议问题