POJ 2676 Sudoku (DFS)

数独,开三个标记,直接暴力,400多mS还是可以接受的

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<sstream>
#include<queue>
#include<cstdio>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int M = 1010;

int vish[15][15];
int visl[15][15];
int vis[15][15];
char s[15][15];
int mp[15][15];
int flag;

int dfs(int x, int y, int sum)
{
	if (flag)
		return 1;

	if (sum == 0)
	{
		for (int i = 0; i < 9; ++i)
		{
			for (int j = 0; j < 9; ++j)
			{
				cout << mp[i][j];
			}
			puts("");
		}

		flag = 1;
		return 1;
	}

	while (mp[x][y] != 0)
	{
		if (y == 8 && x == 8)
			break;
		if (y == 8)
		{
			x++;
			y = 0;
		}
		else
			y++;
	}
	for (int i = 1; i <= 9; ++i)
	{
		if (!vish[x][i] && !visl[y][i] && !vis[(y / 3) + (x / 3) * 3 + 1][i])
		{
			vish[x][i] = 1;
			visl[y][i] = 1;
			vis[(y / 3) + (x / 3) * 3 + 1][i] = 1;
			mp[x][y] = i;
			sum--;
			dfs(x, y, sum);
			sum++;
			vish[x][i] = 0;
			visl[y][i] = 0;
			mp[x][y] = 0;
			vis[(y / 3) + (x / 3) * 3 + 1][i] = 0;


		}

	}

	return 0;
}



int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		memset(visl, 0, sizeof(visl));
		memset(vish, 0, sizeof(vish));
		memset(vis, 0, sizeof(vis));

		for (int i = 0; i < 9; ++i)
		{
			for (int j = 0; j < 9; ++j)
			{
				cin >> s[i][j];
				mp[i][j] = s[i][j] - '0';
			}
		}
		int ans = 0;
		for (int i = 0; i < 9; ++i)
		{
			for (int j = 0; j < 9; ++j)
			{
				//cout << ( j/ 3) + (i / 3) * 3 +1<< " ";
				int tmp = mp[i][j];
				if (tmp == 0)
				{
					ans++;
					continue;
				}

				vish[i][tmp] = 1;
				visl[j][tmp] = 1;
				vis[(j / 3) + (i / 3) * 3 + 1][tmp] = 1;
			}
			//puts("");
		}
		//cout << ans << endl;
		flag = 0;
		dfs(0, 0, ans);


	}

	return 0;

}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/secretbase_/article/details/49511189
个人分类: DFS/BFS POJ
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭