原文:
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.
译文:
在一个N*N矩阵的左上角坐着一个机器人,它只能向右运动或向下运动。那么, 机器人运动到右下角一共有多少种可能的路径?
进一步地,
如果对于其中的一些格子,机器人是不能踏上去的。设计一种算法来获得所有可能的路径。
package chapter_8_Recursion;
import java.util.Scanner;
class Point {
public int x;
public int y;
Point() {
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Question_8_2 {
/**
* @param a
* @param i
* @param j
* @return
*
* 当路径上无障碍计算,从(0,0)开始计算
*
*/
public static int find_Ways(int a[][], int i, int j) {
if(i == (a[i].length-1) || j == (a[i].length-1)) {
return 1;
} else {
return find_Ways(a, i+1, j) + find_Ways(a, i, j+1);
}
}
/**
* @param a
* @param i
* @param j
* @return
*
* 逆向计算,递归方式
*
*/
public static int find_Ways2(int a[][], int i, int j) {
if(i ==0 || j ==0) {
return 1;
} else {
return find_Ways2(a, i-1, j) + find_Ways2(a, i, j-1);
}
}
/**
* @param a
* @param i
* @param j
* @return
*
* 当路径上有障碍计算
*
*/
public static int find_WaysWithBlock(int a[][], int i, int j) {
if(a[i][j] == 1) {
return 0;
}
if(i == (a[i].length-1) && j == (a[i].length-1)) {
return 1;
} else if(i == (a[i].length-1)){
return 0 + find_WaysWithBlock(a, i, j+1);
} else if(j == (a[i].length-1)) {
return find_WaysWithBlock(a, i+1, j) + 0;
} else {
return find_WaysWithBlock(a, i+1, j) + find_WaysWithBlock(a, i, j+1);
}
}
/**
* @param a
* @param num
* @param x
* @param y
* @param road
* @param curIndex
*
* 输出所有符合要求的路径
*
*/
public static void print_AllWays(int a[][], int num, int x, int y, Point road[], int curIndex) {
if(a[x][y] == 1) {
return;
}
Point point = new Point(x, y);
road[curIndex ++] = point;
// 到达目的地,则输出路线
if(x == (num-1) && y == (num-1)) {
for(int i=0; i< curIndex; i++) {
System.out.print("(" + road[i].x + " , " + road[i].y + ") ");
}
System.out.println();
} else {
if(y != (num-1)) {
print_AllWays(a, num, x, y+1, road, curIndex);
}
if(x != (num-1)) {
print_AllWays(a, num, x+1, y, road, curIndex);
}
}
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.nextLine();
Point road[] = new Point[2 * num -1];
for(int i=0; i< 2*num-1; i++) {
road[i] = new Point();
}
int a[][] = new int[num][num];
for(int i=0; i< num; i++) {
String str = scanner.nextLine();
String strs[] = str.split(" ");
for(int j=0 ;j< strs.length; j++) {
a[i][j] = Integer.parseInt(strs[j]);
}
}
int result = find_WaysWithBlock(a, 0, 0);
System.out.println("最终总的路径走法:" + result);
print_AllWays(a, num, 0, 0, road, 0);
}
}