dfs 49 TLE 求优化方法
查看原帖
dfs 49 TLE 求优化方法
1051280
ccc08080楼主2024/10/24 20:51

自己看吧


#include<bits/stdc++.h>
using namespace std;
long long a,s,d[9][9],j,k,l,max1,u,i,y;//d记录,a,s是长和宽
bool f[8][8];//如果f[x][y]选过他的邻居就不能选
bool w(int v,int b){//判断
	return !(f[v-1][b-1]||f[v-1][b]||f[v-1][b+1]||f[v][b-1]||f[v][b]||f[v][b+1]||f[v+1][b-1]||f[v+1][b]||f[v+1][b+1]);
}
int q(int z,int x){//dfs
	l+=d[z][x];
	f[z][x]=1;
	if(l>=max1){
		max1=l;
	}
	for(int g=1;g<=a;g++){
		for(int h=1;h<=s;h++){
			if(w(g,h)) q(g,h);
		}
	}
	l-=d[z][x];
	f[z][x]=0;
	return 0;
}
int main(){
	cin>>y;
	for(int p=0;p<y;p++){
		max1=0;
		l=0;
		cin>>a>>s;
		for(j=0;j<=a+1;j++){
			for(k=0;k<a+2;k++){
				f[j][k]=0;
			}
		}
		for(j=1;j<=a;j++){
			for(k=1;k<=s;k++){
				cin>>d[j][k];
			}
		}
		for(j=1;j<=a;j++){
			for(k=1;k<=s;k++){
				q(j,k);
			}
		}
		cout<<max1<<'\n';
	} 
	
}

2024/10/24 20:51
加载中...