dfs写法
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#define x first
#define y second
using namespace std;
const int N = 6;
typedef pair<int,int> PII;
char str[N][N];
vector<PII> res;
vector<PII> temp;
void turn_all(int r,int c)
{
for(int i=1;i<=4;i++)
{
str[i][c] =(str[i][c] =='-' ? '+' : '-');
str[r][i] =(str[r][i] == '-' ?'+':'-');
}
str[r][c] = (str[r][c]=='-' ?'+':'-');
}
void dfs(int r,int c)
{
if(r==4 && c==5)
{
bool found = true;
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
{
if(str[i][j] =='+')
{
found = false;
break;
}
}
if(found)
{
if(res.empty() || res.size() > temp.size())
res = temp;
}
return;
}
if(c==5)
{
r +=1;
c=1;
}
dfs(r,c+1);
turn_all(r,c);
temp.push_back({r,c});
dfs(r,c+1);
temp.pop_back();
turn_all(r,c);
}
int main()
{
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
cin>>str[i][j];
dfs(1,1);
cout<<res.size()<<endl;
for(int i=0;i<res.size();i++)
cout<<res[i].x<<" "<<res[i].y<<endl;
}
数组位运算写法
用数组位运算时,输入的下标最好从0开始。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#define x first
#define y second
using namespace std;
typedef pair<int,int> PII;
const int N = 6;
char str[N][N],backup[N][N];
vector<PII> res;
int get_num(int r,int c)
{
return 4*r + c;
}
void turn(int r,int c)
{
for(int i=0;i<4;i++)
{
str[i][c] = (str[i][c] =='+' ? '-':'+');
str[r][i] = (str[r][i] =='+' ? '-':'+');
}
str[r][c] = (str[r][c] =='+' ?'-' :'+');
}
int main()
{
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
cin>>str[i][j];
for(int op = 0; op < 1<<16 ;op++)
{
vector <PII> temp;
memcpy(backup,str,sizeof(str));
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
if(op>>get_num(i,j) & 1)
{
temp.push_back({i,j});
turn(i,j);
}
}
bool found = true;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
if(str[i][j] == '+')
{
found = false;
break;
}
}
if(found)
{
if(res.empty() || res.size() > temp.size())
res = temp;
}
memcpy(str,backup,sizeof(str));
}
cout<<res.size()<<"\n";
for(int i=0;i<res.size();i++)
cout<<res[i].x + 1<<' '<<res[i].y + 1<<"\n";
}