Robot go squares (recursive acquaintance and dynamic programming)

topic

X * Y there is a grid of squares and each robot can only take one step to the right or only go down from the top left corner went to the bottom right corner of robots seeking a total number of species moves

ThinkingHere Insert Picture Description

Figure is a 3 * 3 grid, the robot from the top left corner, then take a right to go after the grid is 3 * 2, then go down to go after 2 * 3 grid of squares
whereby the recursion formula can be obtained:
F (X, Y) = F (X, Y -. 1) F + (X -. 1, Y)
when the grid is only one row or column, only one moves
the recursive export x == 1 or y == 1

Dynamic Programming:
dynamic programming according to the recursive rewrite
variable parameters has two recursive stored data for each step two-dimensional array
when x == 1 || y == 1 when, array [x] [y] = 1
otherwise array [x] [y] = array [x - 1] [y] + array [x] [y - 1]

Code

在这里插入代码片/*
 * 有一个X * Y的网格,机器人只能走方格而且每一步只能向右或向下走
 * 求机器人从左上角走到右下角一共有多少种走法
 */
public class Robot {
	public static void main(String[] args) {
		int m = 6;
		int n = 6;
		System.out.println(solution1(m, n));
		System.out.println(solution2(m, n));
	}
	//向右走方格的列数减1,向下走方格的行数减1
	public static int solution1(int x, int y) {  //递归法
		if(x == 1 || y == 1)//只有一行或只有一列时只有一种走法
			return 1;
		else
			return solution1(x, y - 1) + solution1(x - 1, y); 
	}
	public static int solution2(int m, int n) {  //递推法(动态规划)
		int[][] array = new int[m + 1][n + 1];
		for (int i = 1; i < array.length; i++) {
			for (int j = 1; j < array.length; j++) {
				if(i == 1 || j == 1)  //只有一行或者只有一列时只有一种走法
					array[i][j] = 1;
				else
					array[i][j] = array[i][j - 1] + array[i - 1][j];
			}
		}
		return array[m][n];
	}

}

Published 33 original articles · won praise 3 · Views 3781

Guess you like

Origin blog.csdn.net/qq_43169220/article/details/103676910