LeetCode 36. Valid Sudoku
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 36. Valid Sudoku相关的知识,希望对你有一定的参考价值。
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.
首先你要弄懂数独的含义, 就是每行每列最多只能有一个1-9之间的数字,以及上面图中画出的每个小3*3方格也只能最多有一个1-9之间的数字
为了统计每行每列以及每个小3*3方格内数字的个数,我设置了三个向量,同时我们恰好可以用向量的下标来对应数字,用向量的值来统计1-9出现
的次数,如果出现的次数大于1,就说明不是数独
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { vector<int> rowvec(board.size()+1,0); vector<int> columnvec(board.size()+1,0); vector<int> smallvec(board.size()+1,0); vector<int> vec(board.size()+1, 0); for (int i = 0;i < board.size();++i) { for (int j = 0;j < board.size();++j) { if (board[i][j] != ‘.‘) { if(++rowvec[board[i][j]-48]>1)return false; } if (board[j][i] != ‘.‘) { if(++columnvec[board[j][i]-48]>1)return false; } if (i % 3 == 0 && j % 3 == 0) { for(int ii=i;ii<i+3;++ii) for (int jj = j;jj < j + 3;++jj) { if (board[ii][jj] != ‘.‘) if (++smallvec[board[ii][jj] - 48] > 1)return false; } } smallvec=vec; } rowvec = vec; columnvec = vec; } return true; } };
以上是关于LeetCode 36. Valid Sudoku的主要内容,如果未能解决你的问题,请参考以下文章