1. 程式人生 > >【LeetCode】36. Valid Sudoku(C++)

【LeetCode】36. Valid Sudoku(C++)

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

題目:

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

在這裡插入圖片描述

A partially filled sudoku which is valid.

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

Example 1:
在這裡插入圖片描述

Example 2:
在這裡插入圖片描述
Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.
  • The given board contain only digits 1-9 and the character '.'.
  • The given board size is always 9x9.

理解:

判斷給出的數獨是否是有效的。根據給的規則判斷就可以了。
下面兩種實現思想都是一樣的,區別在於第一個第一次迴圈裡判斷行,第二次判斷列,第三次判斷3x3;第二個是一次迴圈把所有的情況判斷完了。

實現1:

class Solution {
public:
	const int boardSize = 9;
	bool isValidSudoku(vector<vector<char>>& board) {
		for (int i = 0; i < boardSize; ++i) {
			if (!isValid(board, i, i+1, 0, 9))
				return false;
			if (!isValid(board, 0, 9, i, i+1))
				return false;
		}
	


		for (int i = 0; i < boardSize; i+=3) {
			for (int j = 0; j < boardSize; j+=3) {
				if (!isValid(board, i, i + 3, j, j + 3))
					return false;
			}
		}
		return true;			
	}

	bool isValid(vector<vector<char>>& board, int x1, int x2, int y1, int y2) {
		bitset<9> b;
		for (int i = x1; i < x2; ++i) {
			for (int j = y1; j < y2; ++j) {
				if (board[i][j] != '.') {
					size_t pos = board[i][j] - '1';
					if (b.test(pos))
						return false;
					else
						b.set(pos);
				}

			}
		}
		return true;
	}
};

實現2:

class Solution {
public:
	const int boardSize = 9;
	bool isValidSudoku(vector<vector<char>>& board) {
		int used1[9][9] = { 0 }, used2[9][9] = { 0 }, used3[9][9] = { 0 };
		for (int i = 0; i < 9; ++i) {
			for (int j = 0; j < 9; ++j) {
				if (board[i][j] != '.') {
					size_t num = board[i][j] - '1';
					size_t k = i / 3 * 3 + j / 3;
					if (used1[i][num] || used2[j][num] || used3[k][num])
						return false;
					used1[i][num] = used2[j][num] = used3[k][num] = 1;
				}
			}
		}
		return true;			
	}
};