WA on #2 #3求助
查看原帖
WA on #2 #3求助
914178
x2317663977楼主2023/10/31 12:34

代码和题解某位大佬差不多,迭代加深,但是就是有两个点过不去

#include <iostream>
using namespace std;
#include <unordered_map>

char g[5][5];
pair<int, int> o1, o2;
int dx[] = { 0,1,0,-1 }, dy[] = { 1,0,-1,0 };

bool check()
{
	for (int i = 0;i < 4;i++)
		if (g[i][0] == g[i][1] && g[i][1] == g[i][2] && g[i][2] == g[i][3]) return true;
	for (int i = 0;i < 4;i++)
		if (g[0][i] == g[1][i] && g[1][i] == g[2][i] && g[2][i] == g[3][i]) return true;
	if (g[0][0] == g[1][1] && g[1][1] == g[2][2] && g[2][2] == g[3][3]) return true;
	if (g[0][3] == g[1][2] && g[1][2] == g[2][1] && g[2][1] == g[3][0]) return true;
	return false;
}

bool dfs(int u, int depth, char last)
{
	if (u == depth)
	{
		if (check()) return true;
		else return false;
	}

	for (int i = 0;i < 4;i++)
	{
		int a = o1.first + dx[i], b = o1.second + dy[i];
		if (a >= 4 || a < 0 || b >= 4 || b < 0) continue;
		if (g[a][b] == last || g[a][b] == 'O') continue;

		swap(g[a][b], g[o1.first][o1.second]);
		swap(a, o1.first);
		swap(b, o1.second);
		if (dfs(u + 1, depth, g[o1.first][o1.second])) return true;
		swap(g[a][b], g[o1.first][o1.second]);
		swap(a, o1.first);
		swap(b, o1.second);
	}

	for (int i = 0;i < 4;i++)
	{
		int a = o2.first + dx[i], b = o2.second + dy[i];
		if (a >= 4 || a < 0 || b >= 4 || b < 0) continue;
		if (g[a][b] == last || g[a][b] == 'O') continue;

		swap(g[a][b], g[o2.first][o2.second]);
		swap(a, o2.first);
		swap(b, o2.second);
		if (dfs(u + 1, depth, g[o2.first][o2.second])) return true;
		swap(g[a][b], g[o2.first][o2.second]);
		swap(a, o2.first);
		swap(b, o2.second);
	}

	return false;
}

int main()
{
	for (int i = 0;i < 4;i++) cin >> g[i];

	o1.first = -1;
	for (int i = 0;i < 4;i++)
		for (int j = 0;j < 4;j++)
		{
			if (g[i][j] == 'O' && o1.first == -1)
				o1 = { i,j };
			else if (g[i][j] == 'O')
				o2 = { i,j };
		}

	int depth = 0;
	while (!dfs(0, depth, 'N')) depth++;
	cout << depth << endl;
	return 0;
}
2023/10/31 12:34
加载中...