全TLE求助
查看原帖
全TLE求助
1300695
shenyicheng楼主2025/1/9 14:04
#include <bits/stdc++.h>
using namespace std;
bool a[10][10];
bool l = 0;
int cnt = 0;
int ans = INT_MAX;
void dfs(int x,int a1,int b1){
	if(x >= ans)return;
	if(cnt == 25){
		//cout << x << " ";
		ans = min(ans,x);
		l = 1;
		return;
	}
	if(x > 6)return;
	for(int i = 1;i <= 5;i++){
		for(int j = 1;j <= 5;j++){
			if(i == a1 && j == b1)continue;
			if(a[i][j] == 1 || a[i][j] == 0){
				bool d = 1;
				if(i > 1){
					if(a[i - 1][j] == 0)d = 0;
				}
				if(j > 1){
					if(a[i][j - 1] == 0)d = 0;
				}
				if(i < 5){
					if(a[i + 1][j] == 0)d = 0;
				}
				if(j < 5){
					if(a[i][j + 1] == 0)d = 0;
				}
				if(d == 1)continue;
			}
			bool o1 = a[i][j];
			bool o2 = a[i - 1][j];
			bool o3 = a[i][j - 1];
			bool o4 = a[i][j + 1];
			bool o5 = a[i + 1][j];
			int o8 = cnt;
			if(a[i][j] == 1){
				a[i][j] = 0;
				cnt--;
			}else{
				a[i][j] = 1;
				cnt++;
			}
			if(i > 1){
				if(a[i - 1][j] == 1){
					a[i - 1][j] = 0;
					cnt--;
				}else{
					a[i - 1][j] = 1;
					cnt++;
				}
			}
			if(j > 1){
				if(a[i][j - 1] == 1){
					a[i][j - 1] = 0;
					cnt--;
				}else{
					a[i][j - 1] = 1;
					cnt++;
				}
			}
			if(j < 5){
				if(a[i][j + 1] == 1){
					a[i][j + 1] = 0;
					cnt--;
				}else{
					a[i][j + 1] = 1;
					cnt++;
				}
			}
			if(i < 5){
				if(a[i + 1][j] == 1){
					a[i + 1][j] = 0;
					cnt--;
				}else{
					a[i + 1][j] = 1;
					cnt++;
				}
			}
			
			//cout << cnt << " ";
			dfs(x + 1,i,j);
			a[i][j] = o1;
			a[i - 1][j] = o2;
			a[i][j - 1] = o3;
			a[i][j + 1] = o4;
			a[i + 1][j] = o5;
			cnt = o8;
		}
	}
}
int main()
{
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	//ios::sync_with_stdio(0);
	//cin.tie(0);
	int n;
	cin >> n;
	for(int i = 1;i <= n;i++){
		ans = INT_MAX;
		cnt = 0;
		l = 0;
		for(int j = 1;j <= 5;j++){
			for(int k = 1;k <= 5;k++){
				char s;
				cin >> s;
				a[j][k] = int(s - '0');
				if(a[j][k] == 1)cnt++;
			}
		}
		/*for(int j = 1;j <= 5;j++){
			for(int k = 1;k <= 5;k++){
				cout << a[j][k];
			}
			cout << endl;
		}*/
		//if(cnt == 24)cout << "-1" << endl;
		dfs(1,0,0);
		if(l == 0)cout << "-1" << endl;
		else cout << ans - 1<< endl;
		
	}
	return 0;
}

2025/1/9 14:04
加载中...