蒟蒻膜你和dfs做的,求助
查看原帖
蒟蒻膜你和dfs做的,求助
297798
FANTA5TlC楼主2020/11/12 21:09

这是膜你

#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[1005][1005];
bool v[1005][1005];
bool f1, f2, f3;
int ax, ay, az, x, y;
void go(string s){
	if (s == "right"){
		ax = x;
		ay = y + 1;
		az = a[x][y + 1];
	}
	if (s == "up"){
		ax = x - 1;
		ay = y;
		az = a[x - 1][y];
	}
	if (s == "down"){
		ax = x + 1;
		ay = y;
		az = a[x + 1][y];
	}
}
int main(){
	cin >> n >> m;
	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= m; ++j)
			cin >> a[i][j];
	x = y = 1;
	int ans = 0;
	while (x <= n && y <= m){
		v[x][y] = true;
		f1 = f2 = f3 = false;
		string s;
		if (x + 1 <= n && v[x + 1][y] == false) f1 = true;
		if (x - 1 >= 1 && v[x - 1][y] == false) f2 = true;
		if (y + 1 <= m && v[x][y + 1]) f3 = true;
		if (f1 && f2 && f3){
			if (a[x + 1][y] > a[x - 1][y] && a[x + 1][y] > a[x][y + 1]) s = "down";
			if (a[x][y + 1] > a[x - 1][y] && a[x][y + 1] > a[x + 1][y]) s = "right";
			if (a[x - 1][y] > a[x + 1][y] && a[x - 1][y] > a[x][y + 1]) s = "up";
		} else if (f1 && f2){
			if (a[x - 1][y] < a[x + 1][y]) s = "down";
			if (a[x - 1][y] > a[x + 1][y]) s = "up";
		} else if (f1 && f3){
			if (a[x][y + 1] > a[x + 1][y]) s = "right";
			if (a[x][y + 1] < a[x + 1][y]) s = "down";
		} else if (f2 && f3){
			if (a[x][y + 1] > a[x - 1][y]) s = "right";
			if (a[x][y + 1] < a[x - 1][y]) s = "up";
		} else if (f1) s = "down";
		else if (f2) s = "up";
		else s = "right";
		go(s);
		x = ax;
		y = ay;
		ans += a[x][y];
	}
	cout << ans + a[n][m] << endl;
}

这是dfs

#include <iostream>
using namespace std;
int a[1005][1005];
bool f[1005][1005];
int n, m;
int ans;
int maxx = -100000;
void dfs(int x, int y){
	if (x == n && y == m){
		maxx = max(maxx, ans);
		return;
	}
	if (x < 1 || y < 1 || x > n || y > m) return;
	if (f[x][y] == true) return;
	f[x][y] = true;
	ans += a[x][y];
	dfs(x - 1, y);
	dfs(x + 1, y);
	dfs(x, y + 1);
	ans -= a[x][y];
	f[x][y] = false;
}
int main(){
	cin >> n >> m;
	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= m; ++j)
			cin >> a[i][j];
	dfs(1, 1);
	cout << maxx << endl;
}
2020/11/12 21:09
加载中...