标签:interview
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.
标签:interview
原文地址:http://7371901.blog.51cto.com/7361901/1584896