#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
int board[5][5];//棋盘定义
int movex[5] = { 0,-1,0,1,0 },
movey[5] = { 0,0,1,0,-1 };//移动坐标 不动 左 上 右 下
int o_x1, o_y1, //第一个空格坐标
o_x2, o_y2, //第二个空格坐标
max_level, //dfs搜索最大层数
f; //结果标志
int can_move(int a, int b, int k) {
//如果移动后的空格的坐标的颜色和操作人的颜色不同并且此次移动该空格还在棋盘内 则此次操作可以进行否则不能进行 (例如持黑色棋子先移动则他应该移动白子)
if (board[a][b] != k && a >= 1 && a <= 4 && b >= 1 && b <= 4) return 1;
else return 0;
}
int is_win() {
for (int i = 1; i <= 4; i++) {
//行
if (board[i][1] == board[i][2] && board[i][2] == board[i][3] && board[i][3] == board[i][4]) return 1;
//列
if (board[1][i] == board[2][i] && board[2][i] == board[3][i] && board[3][i] == board[4][i]) return 1;
}
//对角线
if (board[1][1] == board[2][2] && board[2][2] == board[3][3] && board[3][3] == board[4][4]) return 1;
if (board[1][4] == board[2][3] && board[2][3] == board[3][2] && board[3][2] == board[4][1]) return 1;
return 0;
}
void dfs(int x1, int y1, int x2, int y2, int pre, int level) {
if (is_win()) {
f = 1;
return;
}
else if (level > max_level) return;
for (int i = 1; i <= 4; i++) {
int nx = x1 + movex[i];
int ny = y1 + movey[i];
int np = x2 + movex[i];
int nq = y2 + movey[i];
//移动第一个空格
if (can_move(nx, ny, pre)) {
//交换空格和要替换的位置
swap(board[x1][y1], board[nx][ny]);
//对手再进行移动
dfs(nx, ny, x2, y2, board[x1][y1], level + 1);
//移动结束恢复原来的位置 如果 f 不为0 说明找到结果
swap(board[x1][y1], board[nx][ny]);
}
//移动第二个空格
if (can_move(np, nq, pre)) {
//交换空格和要替换的位置
swap(board[x2][y2], board[np][nq]);
//对手再进行移动
dfs(x1, y1, np, nq, board[x2][y2], level + 1);
//移动结束恢复原来的位置 如果 f 不为0 说明找到结果
swap(board[x2][y2], board[np][nq]);
}
}
}
int main() {
//数据准备构造棋盘格 1 代表 黑 2 代表白 3代表空
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
char ch;
cin >> ch;
if (ch == 'B') board[i][j] = 1;
else if (ch == 'W') board[i][j] = 2;
else {
board[i][j] = 3;
if (!o_x1) {
o_x1 = i, o_y1 = j;
}
else {
o_x2 = i, o_y2 = j;
}
}
}
}
//采用迭代加深搜索算法计算
for (max_level = 0;; max_level++) {
dfs(o_x1,o_y1,o_x2,o_y2, 1, 1);//黑色先手 1
dfs(o_x1,o_y1,o_x2,o_y2, 2, 1);//白色先手 2
//f不为0说明找到移动次数
if (f) {
printf("%d", max_level);
return 0;
}
}
return 0;
}