Leetcode Note: Valid Sudoku
I. Description
Determine if a Sudoku is valid, according to: Sudoku Puzzles-The Rules:
Http://sudoku.com.au/TheRules.aspx.
The Sudoku board cocould be partially filled, where empty cells are filled with the character '.'.
The following figure: A partially filled sudoku which is valid.
Ii. Question Analysis
The Sudoku matrix can be summarized as follows: for each row, column, and3×3
Are there any unique0~9
Arrangement and combination. If the same element exists, the Sudoku matrix is invalid.
This is a simple question, that is, to traverse all elements of the Sudoku matrix and check whether each element meets the nature of Sudoku. To determine whether an element is in a row, a column, or a residential area, I define ~ 9. number of occurrencesmap
, Use'1','2',...,'9'
As long as the storage object of a keyword is greater than 1, it indicates3×3
There is a duplicate keyword in the jiugongge area of. In this way, the traversal can be used to determine whether the matrix is legal.
Iii. Sample Code
#include
#include
#include
using namespace std;class Solution{public: bool isValidSudoku(vector
>& board) { map
sudokuMap; for (int i = 0; i < 9; i++) { sudokuMap.clear(); for (int j = 0; j < 9; j++) { sudokuMap[board[i][j]]++; if ((board[i][j] != '.') && (sudokuMap[board[i][j]] > 1)) return false; } } for (int i = 0; i < 9; i++) { sudokuMap.clear(); for (int j = 0; j < 9; j++) { sudokuMap[board[j][i]]++; if ((board[j][i] != '.') && (sudokuMap[board[j][i]] > 1)) return false; } } for (int i = 0; i < 9; i += 3) { for (int j = 0; j < 9; j += 3) { sudokuMap.clear(); for (int k = i; k < i + 3; k++) { for (int l = j; l < j + 3; l++) { sudokuMap[board[k][l]]++; if ((board[k][l] != '.') && (sudokuMap[board[k][l]] > 1)) return false; } } } } return true; }};
The running result is as follows:
1. A correct Sudoku matrix:
2. An incorrect Sudoku matrix:
Iv. Summary
This question does not require any algorithm. You only need to design matrix operations and usemap
Used to store each row, column, or cell.1~9
The number of times each number appears. If a Sudoku is found to be larger than one, the Sudoku is immediately denied. valid sudoku is determined only when the Sudoku matrix is traversed and meets the requirements.