1. 程式人生 > >36. Valid Sudoku

36. Valid Sudoku

題意:

測試一個9*9的數獨是否合法。

思路:

暴力求解,先測試每行,再測試每列,最後測試每塊。遇到不合法直接返回false;

bool isValidSudoku(vector<vector<char>>& board) {
	set<char> t({ '1','2','3','4','5','6','7','8','9' });
	for (int i = 0; i < 9; ++i) {
		set<char> a = t;
		for (int j = 0; j < 9; ++j)
			if (board[i][j] == '.')
				continue;
			else if (a.count(board[i][j]) == 0){
				cout << "1";
				return false;
			}
				
			else
				a.erase(board[i][j]);
	}
	for (int i = 0; i < 9; ++i) {
		set<char> a = t;
		for (int j = 0; j < 9; ++j)
			if (board[j][i] == '.')
				continue;
			else if (a.count(board[j][i]) == 0) {
				cout << "2";
				return false;
			}
			else
				a.erase(board[j][i]);
	}

	for (int i = 0; i < 9; ++i) {
		set<char> a = t;
		for (int j = 0; j < 9; ++j)
			if (board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3] == '.')
				continue;
			else if (a.count(board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]) == 0){
				cout << "3";
				return false; 
			}
			else
				a.erase(board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]);
	}
	return true;

}