从零开始的LC刷题(126): Valid Sudoku

mac2024-05-28  57

原题:

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

Each row must contain the digits 1-9 without repetition.Each column must contain the digits 1-9 without repetition.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 '.'.

检查数独是否合法(即合乎规定123),暴力求解结果:

Success

Runtime: 12 ms, faster than 89.91% of C++ online submissions for Valid Sudoku.

Memory Usage: 9.3 MB, less than 100.00% of C++ online submissions for Valid Sudoku.

代码:

class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { for(int i=0;i<9;i++){ bool hash[10]={0}; for(int j=0;j<9;j++){ if(board[i][j]=='.'){continue;} if(!hash[board[i][j]-'0']){hash[board[i][j]-'0']=1;} else return false; } } for(int i=0;i<9;i++){ bool hash[10]={0}; for(int j=0;j<9;j++){ if(board[j][i]=='.'){continue;} if(!hash[board[j][i]-'0']){hash[board[j][i]-'0']=1;} else return false; } } for(int i=0;i<9;i+=3){ for(int j=0;j<9;j+=3){ bool hash[10]={0}; for(int m=0;m<3;m++){ for(int n=0;n<3;n++){ if(board[i+m][j+n]=='.'){continue;} if(!hash[board[i+m][j+n]-'0']){hash[board[i+m][j+n]-'0']=1;} else return false; } } } } return 1; } };

看solution可以一趟全检查完,方法是一开始就创建三个9*9的哈希表,但是它们的意义各不相同,一个是纵向代表第n行横向是哈希表,一个是纵向代表第n列的哈希表,另一个是把3*3的小方块标号0-8,每行分别是一个小方块n的哈希表,而这个n可以由数字所在的位置推算出:n=x*3+y/3*3,注意是整数运算,结果:

Success

Runtime: 12 ms, faster than 89.91% of C++ online submissions for Valid Sudoku.

Memory Usage: 9.1 MB, less than 100.00% of C++ online submissions for Valid Sudoku.

代码:

class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { bool vhash[9][9]={0}; bool hhash[9][9]={0}; bool shash[9][9]={0}; for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ if(board[i][j]=='.'){continue;} int k=i/3+j/3*3; int index=board[i][j]-'0'-1; if(!vhash[i][index]&&!hhash[j][index]&&!shash[k][index]){ vhash[i][index]=1; hhash[j][index]=1; shash[k][index]=1; } else return 0; } } return 1; } };

 

最新回复(0)