T1194:移动路线

【题目描述】

X桌子上有一个m行n列的方格矩阵,将每个方格用坐标表示,行坐标从下到上依次递增,列坐标从左至右依次递增,左下角方格的坐标为(1,1),则右上角方格的坐标为(m,n)。

小明是个调皮的孩子,一天他捉来一只蚂蚁,不小心把蚂蚁的右脚弄伤了,于是蚂蚁只能向上或向右移动。小明把这只蚂蚁放在左下角的方格中,蚂蚁从

   左下角的方格中移动到右上角的方格中,每步移动一个方格。蚂蚁始终在方格矩阵内移动,请计算出不同的移动路线的数目。

   对于1行1列的方格矩阵,蚂蚁原地移动,移动路线数为1;对于1行2列(或2行1列)的方格矩阵,蚂蚁只需一次向右(或向上)移动,移动路线数也为1……对于一个2行3列的方格矩阵,如下图所示:

(2,1) (2,2) (2,3)
(1,1) (1,2) (1,3)

蚂蚁共有3种移动路线:

路线1:(1,1) → (1,2) → (1,3) → (2,3)

路线2:(1,1) → (1,2) → (2,2) → (2,3)

路线3:(1,1) → (2,1) → (2,2) → (2,3)

【输入】

输入只有一行,包括两个整数m和n(0 < m+n ≤ 20),代表方格矩阵的行数和列数,m、n之间用空格隔开。

【输出】

输出只有一行,为不同的移动路线的数目。

【输入样例】

2 3

【输出样例】

3

解题思路:

这道题我刚开始第一反应,深搜,后来...也能用递推...

比如从(1, 1) 到 (2, 3) 就是到(2, 2)的路线数加上到(1, 3)的路线数;

DFS代码:

#include<iostream>
using namespace std;
int book[110][110];
int row, col, cnt = 0;
struct point{
	int x, y;
}p[] = {{1, 0}, {0, 1}};
void dfs(int x, int y){
	if(x == row && y == col){
		cnt++;
		return ;
	}
	for(int i = 0; i < 2; i++){
		int tx = x + p[i].x, ty = y + p[i].y;
		if(tx > row || ty > col)	continue;
		if(!book[tx][ty]){
			book[tx][ty] = 1;
			dfs(tx, ty);
			book[tx][ty] = 0;
		}
	}
} 
int main(){
	// 只能 向上或者向右
	cin >> row >> col;
	dfs(1, 1);
	cout << cnt << endl;
	return 0;
}

递推代码:

#include<iostream>
using namespace std;
int f(int x, int y){
	if(x == 1 || y == 1)	return 1;
	return f(x - 1, y) + f(x, y - 1);
}
int main(){
	int row, col;
	cin >> row >> col;
	cout << f(row, col) << endl; 
	return 0; 
} 

猜你喜欢

转载自blog.csdn.net/weixin_42522886/article/details/89184453
今日推荐