leetcode Valid Sudoku

题目连接

https://leetcode.com/problems/valid-sudoku/ 

Valid Sudoku

Description

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

A partially filled sudoku which is valid.

 

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

直接判断。。

class Solution {
public:
	static const int N = 9;
	bool isValidSudoku(vector<vector<char>>& board) {
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				if (board[i][j] == '.') continue;
				if (!isOk(board, i, j, board[i][j])) return false;
			}
		}
		return true;
	}
	bool isOk(vector<vector<char>>& board, int x,int y,char ch) {
		int vis[3][N + 1] = { 0 };
		for (int i = 0; i < N; i++) {
			if (board[x][i] != '.') {
				vis[0][board[x][i] - '0']++;
			}
			if (board[i][y] != '.') {
				vis[1][board[i][y] - '0']++;
			}
		}
		for (int i = x / 3 * 3; i <= x / 3 * 3 + 2; i++) {
			for (int j = y / 3 * 3; j <= y / 3 * 3 + 2; j++) {
				if (board[i][j] != '.') {
					vis[2][board[i][j] - '0']++;
				}
			}
		}
		for (int i = 1; i <= N; i++) {
			if (vis[0][i] > 1 || vis[1][i] > 1 || vis[2][i] > 1) return false;
		}
		return true;
	}
};
posted @ 2015-12-11 20:44  GadyPu  阅读(171)  评论(0编辑  收藏  举报