Popular Posts

Monday, July 18, 2011

Robot in an NXN grid

Problem:

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 robot?
FOLLOW UP
Imagine certain squares are “off limits”, such that the robot can not step on them. Design an algorithm to get all possible paths for the robot.

Solution:

  • Start from (0,0)
  • Robot can take right? i.e in boundary and cell is not marked as "off limits"
  • Then take right
  • Robot can take left? i.e in boundary and cell is not marked as "off limits"
  • Then take left
  • Do these steps recursively until destination is found or no path is found.
  • return possible steps.

It can be derived in mathematical way as follows:

Result will be like this,

1 + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+..+N)
which can be written as,









Finally, it can be expressed as follows,


Complexity: O(N^2)
Code:

2 comments:

  1. could you send me complete program.please send main function also it will help in understanding this code more.

    ReplyDelete
  2. please send me the code in prakhardubey95@gmail.com

    ReplyDelete