版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Fantasy_World/article/details/82917070
难点是想到颜色可以为O,搜索的过程中可能会把一个O移动到另一个O上面,然后搜索的颜色参数就变成O就错了。。。
也没什么好办法,就是判到O直接跳过。。。
另外,要习惯把各种量写在参数表里,这样能省很多代码。。。也更好调试
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
#include <queue>
#include <map>
using namespace std;
#define debug(x) cerr << #x << "=" << x << endl;
const int MAXN = 200000 + 10;
typedef long long ll;
char gra[10][10];
int ans,deg,x1,y1,x2,y2;
bool flg;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
bool check() {
for(int i=1; i<=4; i++) {
if(gra[i][1] == gra[i][2] && gra[i][2] == gra[i][3] && gra[i][3] == gra[i][4])
return true;
}
for(int j=1; j<=4; j++) {
if(gra[1][j] == gra[2][j] && gra[2][j] == gra[3][j] && gra[3][j] == gra[4][j])
return true;
}
if(gra[1][1] == gra[2][2] && gra[2][2] == gra[3][3] && gra[3][3] == gra[4][4])
return true;
if(gra[1][4] == gra[2][3] && gra[2][3] == gra[3][2] && gra[3][2] == gra[4][1])
return true;
return false;
}
bool id_dfs(int x, int deg, int x1, int y1, int x2, int y2, char col) {
if(x == deg + 1) {
if(check()) return true;
else return false;
}
for(int i=0; i<=3; i++) {
int nx1 = x1 + dx[i];
int ny1 = y1 + dy[i];
int nx2 = x2 + dx[i];
int ny2 = y2 + dy[i];
if(nx1 >= 1 && nx1 <= 4 && ny1 >= 1 && ny1 <= 4 && gra[nx1][ny1] != col && gra[nx1][ny1] != 'O') {
swap(gra[x1][y1], gra[nx1][ny1]);
if(id_dfs(x+1, deg, nx1, ny1, x2, y2, gra[x1][y1])) return true;
swap(gra[x1][y1], gra[nx1][ny1]);
}
if(nx2 >= 1 && nx2 <= 4 && ny2 >= 1 && ny2 <= 4 && gra[nx2][ny2] != col && gra[nx2][ny2] != 'O') {
swap(gra[x2][y2], gra[nx2][ny2]);
if(id_dfs(x+1, deg, x1, y1, nx2, ny2, gra[x2][y2])) return true;
swap(gra[x2][y2], gra[nx2][ny2]);
}
}
return false;
}
int main() {
for(int i=1; i<=4; i++) {
for(int j=1; j<=4; j++) {
cin >> gra[i][j];
if(gra[i][j] == 'O') {
if(x1 == 0) {
x1 = i, y1 = j;
} else {
x2 = i, y2 = j;
}
}
}
}
while(1) {
++deg;
if(id_dfs(1, deg, x1, y1, x2, y2, 0)) {
printf("%d", deg);
break;
}
}
return 0;
}