首页 > 其他 > 详细

CC150 8.2

时间:2014-12-01 10:15:42      阅读:279      评论:0      收藏:0      [点我收藏+]

8.2 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.

class Pos
{
  int x;
  int y;
}

interface Robot
{
  Pos getPos();
  void right();
  void down();  
}

path(i, j) means how many path goes to Pos(i, j). Thus,
path(i, j) = path(i - 1, j) + path(i , j - 1);
path(0, 1) = path(1, 0) = 1;

int path(int i, int j)
{
  if ((i == 0 && j == 1) || (i == 1 && j == 0))
    return 1;
  else
    return path(i - 1, j) + path(i, j - 1);
}

// If some squares are off limits.
// Thus.
path(x, y) = 0, if Pos(x, y) are the squares.

int path(int i, int j, Set<Pos> offLimits)
{
  if (offLimits.contains(Pos.at(i, j)))
    return 0;
  else if ((i == 0 && j == 1) || (i == 1 && j == 0))
    return 1;
  else
    return path(i - 1, j) + path(i, j - 1);
}


// How to get all possible paths?

// Define a path node, like list node.
class PathNode
{
  Pos pos;
  PathNode next;
}


PathNode run(PathNode node, Set<Pos> bombs, Pos target)
{
  Validate.notNull(node);
  Validate.notNull(target);

  // Reach target
  if (target.equals(node.getPos()))
    return node;
  
  // This position is a bomb
  if (bombs != null && bombs.contains(node.getPos()))
    return null;
  
  Node right = run(new PathNode(node.right());
  if (right != null)
    node.addNext(right);
    
  Node down = run(new PathNode(node.down()));
  if (down != null)
    node.addNext(down);
    
  return node;
}

// Return a tree, each path is the path.


CC150 8.2

原文:http://7371901.blog.51cto.com/7361901/1584896

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!