关闭屏幕 DFS
关闭屏幕,求最小关闭次数,应该用BFS更好,但此处DFS更容易理解
#include <bits/stdc++.h>
using namespace std;
vector<int> path;
vector<vector<int> > cur;
vector<int> pat;
int n;
int flag = 0;
bool isVaild(){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(cur[i][j] == 1) return false;
}
}
return true;
}
void flip(int cnt){
int i = cnt / n;
int j = cnt % n;
cur[i][j] = !cur[i][j];
int next[4][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
for(int k = 0; k < 4; k++){
int ni = i + next[k][0];
int nj = j + next[k][1];
if(ni >= 0 && ni < n && nj >= 0 && nj < n){
cur[ni][nj] = !cur[ni][nj];
}
}
return ;
}
void dfs(int cnt, int num){
if(isVaild()){
flag = 1;
cout << "Vaild"<<endl;
for(int i = 0; i < num; i++){
cout << pat[i]<<endl;
}
return ;
}
if(cnt >= n*n) return;
dfs(cnt+1, num);
if(flag) return ;
flip(cnt);
//cout << num << " " <<cnt<<endl;
pat[num] = cnt;
//if(num == 0) cout << "-----"<<cnt<<endl;
dfs(cnt+1, num+1);
flip(cnt);
}
void answer(vector<vector<int> >& status)
{
pat.resize(n*n, 0);
dfs(0, 0);
}
int main(){
cin >> n;
vector<vector<int> > status(n, vector<int>(n));
cur.resize(n);
for(int i = 0;i < n; i++){
cur[i].resize(n);
}
for(int i = 0; i < n; i ++){
for(int j = 0; j < n; j++){
cin >> status[i][j] ;
cur[i][j] = status[i][j];
}
}
answer(status);
return 0;
}
/*
4
0 1 0 0
1 0 0 0
1 1 0 1
0 1 1 0
2
0 0
1 0
*/