Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

Re:1922ms的dfs,好险!!!

Posted by cisjiong at 2012-07-29 21:03:56 on Problem 2676
In Reply To:Re:1922ms的dfs,好险!!! Posted by:lileiyang12 at 2011-04-15 15:00:59
1391MS
#include <cstdio>
using namespace std;

char sudoku[10][10];

bool judge(int i, int j, char v) {
	for (int k = 0; k < 9; ++k) {
		if (sudoku[k][j] == v) return false;
		if (sudoku[i][k] == v) return false;
	}

	int ii = i / 3, jj = j / 3;

	for (int _i = ii * 3; _i < ii * 3 + 3; ++_i) {
		for (int _j = jj * 3; _j < jj * 3 + 3; ++_j) {
			if (sudoku[_i][_j] == v)
				return false;
		}
	}

	return true;
}

bool dfs(int idx) {
	if (idx == 81) {
		for (int i = 0; i < 9; ++i) 
			printf("%s\n", sudoku[i]);
		return true;
	}

	int r = idx / 9, c = idx % 9;
	if (sudoku[r][c] != '0') return dfs(idx + 1);

	for (int i = 1; i <= 9; ++i) {
		if (judge(r, c, '0' + i)) {
			sudoku[r][c] = (i + '0');
			if (dfs(idx + 1)) return true;
			sudoku[r][c] = '0';
		}
	}

	return false;
}

int main() {
	int n;
	scanf ("%d", &n);

	while (n--) {
		for (int i = 0; i < 9; ++i)
			scanf ("%s", sudoku[i]);

		dfs(0);
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator