POJ 2676 解题报告

这道题是DFS。看了discuss,说是倒着搜。从8,8到0,0,应该是根据测试数据来的。

thestoryofsnow2676Accepted132K16MSC++2172B
/* 
ID: thestor1 
LANG: C++ 
TASK: poj2676 
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>

using namespace std;

bool bexists[3][3][9], rexists[9][9], cexists[9][9];

void printSudoku(char sudoku[][9])
{
	// printf("[debug]sudoku:\n");
	for (int r = 0; r < 9; ++r)
	{
		for (int c = 0; c < 9; ++c)
		{
			printf("%c", sudoku[r][c]);
		}
		printf("\n");
	}
}

bool solveSudoku(char sudoku[][9], int r, int c)
{
	if (c == -1)
	{
		c = 8;
		r--;
		if (r == -1)
		{
			return true;
		}
	}

	// printf("[debug]r: %d, c: %d\n", r, c);

	int br = r / 3, bc = c / 3;
	if (sudoku[r][c] == '0')
	{
		for (int n = 1; n <= 9; ++n)
		{
			if (bexists[br][bc][n - 1] || rexists[r][n - 1] || cexists[c][n - 1])
			{
				continue;
			}
			bexists[br][bc][n - 1] = true;
			rexists[r][n - 1] = true;
			cexists[c][n - 1] = true;
			if (solveSudoku(sudoku, r, c - 1))
			{
				sudoku[r][c] = n + '0';
				return true;
			}
			bexists[br][bc][n - 1] = false;
			rexists[r][n - 1] = false;
			cexists[c][n - 1] = false;
		}

		// tried all possible candidates and failed
		return false;
	}
	else 
	{
		return solveSudoku(sudoku, r, c - 1);
	}
}

int main()
{
	int T;	
	scanf("%d", &T);
	char sudoku[9][9];
	for (int t = 0; t < T; ++t)
	{
		for (int r = 0; r < 9; ++r)
		{
			scanf("%s", sudoku[r]);
		}

		// printSudoku(sudoku);

		for (int r = 0; r < 9; ++r)
		{
			for (int n = 0; n < 9; ++n)
			{
				rexists[r][n] = false;
				cexists[r][n] = false;
			}
		}

		for (int br = 0; br < 3; ++br)
		{
			for (int bc = 0; bc < 3; ++bc)
			{
				for (int n = 0; n < 9; ++n)
				{
					bexists[br][bc][n] = false;
				}
			}
		}

		for (int r = 0; r < 9; ++r)
		{
			for (int c = 0; c < 9; ++c)
			{
				int n = sudoku[r][c] - '0';
				int br = r / 3, bc = c / 3;
				if (n != 0)
				{
					bexists[br][bc][n - 1] = true;
					rexists[r][n - 1] = true;
					cexists[c][n - 1] = true;
				}
			}
		}

		solveSudoku(sudoku, 8, 8);
		
		printSudoku(sudoku);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值