【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;			
	}
};

猜你喜欢

转载自blog.csdn.net/Ethan95/article/details/84557894