90:滑雪

90:滑雪

题目链接http://noi.openjudge.cn/ch0206/90/

思路: DFS+记忆,不记忆会超时,并且深搜下去得到的结果就是该点的最优值。所以可以使用记忆来减少重复次数。

#include<iostream>
#include<algorithm>
using namespace std;
int a[110][110] = {
    
     0 }, b[110][110] = {
    
     0 };
int r, c;
int dfs(int x, int y) {
    
    
	int temp = 0;
	if (x - 1 > 0 && a[x - 1][y] < a[x][y]) {
    
    
		if (b[x - 1][y]) {
    
    
			temp = max(temp, b[x - 1][y]);
		}
		else {
    
    
			temp = max(temp, dfs(x - 1, y));
		}
	}
	if (x + 1 <= r && a[x + 1][y] < a[x][y]) {
    
    
		if (b[x + 1][y]) {
    
    
			temp = max(temp, b[x + 1][y]);
		}
		else {
    
    
			temp = max(temp, dfs(x + 1, y));
		}
	}
	if (y - 1 > 0 && a[x ][y - 1] < a[x][y]) {
    
    
		if (b[x][y - 1]) {
    
    
			temp = max(temp, b[x ][y - 1]);
		}
		else {
    
    
			temp = max(temp, dfs(x , y - 1));
		}
	}
	if (y+ 1 <= r && a[x ][y + 1] < a[x][y]) {
    
    
		if (b[x ][y + 1]) {
    
    
			temp = max(temp, b[x ][y + 1]);
		}
		else {
    
    
			temp = max(temp, dfs(x , y + 1));
		}
	}
	b[x][y] = temp + 1;
	return temp + 1;
}
int main() {
    
    

	cin >> r >> c;
	for (int i = 1; i <= r; i++) {
    
    
		for (int j = 1; j <= c; j++) {
    
    
			cin >> a[i][j];
		}
	}
	int maxx = 0;
	for (int i = 1; i <= r; i++) {
    
    
		for (int j = 1; j <= c; j++) {
    
    
			if (!b[i][j])
				maxx = max(maxx, dfs(i, j));
			else//其实这个else是可以省去的,自行大脑补充
				maxx=max(maxx,b[i][j]);
		}
	}
	cout << maxx;
	return 0;
}

代码里的四个方向可以用方向数组来减少重复代码量

#include<iostream>
#include<algorithm>
using namespace std;
int a[110][110] = {
    
     0 }, b[110][110] = {
    
     0 };
int r, c;
int fx[4][2] = {
    
     {
    
    0,1},{
    
    0,-1},{
    
    1,0},{
    
    -1,0} };
bool fw(int x, int y) {
    
    
	if (x >= 1 && x <= r && y >= 1 && y <= c)
		return true;
	return false;
}
int dfs(int x, int y) {
    
    
	if (b[x][y]) {
    
    
		return b[x][y];
	}
	int temp = 0;
	int tx, ty;
	for (int i = 0; i < 4; i++) {
    
    
		tx =x+ fx[i][0], ty =y+ fx[i][1];
		if(fw(tx,ty)&&a[tx][ty]<a[x][y])
			temp = max(temp, dfs(tx,ty));
	}
	b[x][y] = temp + 1;
	return temp + 1;
}
int main() {
    
    
	
	cin >> r >> c;
	for (int i = 1; i <= r; i++) {
    
    
		for (int j = 1; j <= c; j++) {
    
    
			cin >> a[i][j];
		}
	}
	int maxx = 0;
	for (int i = 1; i <= r; i++) {
    
    
		for (int j = 1; j <= c; j++) {
    
    
				maxx = max(maxx, dfs(i, j));
		}
	}
	cout << maxx;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46028214/article/details/113054500
90
今日推荐