https://leetcode.com/problems/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.
class Solution { public: vector<int> getIdx(int i, int j) { vector<int> idx(4); int row, col; if(i>=0 && i<=2) { idx[0] = 0; idx[1] = 2; } else if(i>=3 && i<=5) { idx[0] = 3; idx[1] = 5; } else if(i>=6 && i<=8) { idx[0] = 6; idx[1] = 8; } if(j>=0 && j<=2) { idx[2] = 0; idx[3] = 2; } else if(j>=3 && j<=5) { idx[2] = 3; idx[3] = 5; } else if(j>=6 && j<=8) { idx[2] = 6; idx[3] = 8; } return idx; } bool checkRowAndColumn(vector<vector<char>>& board, int i, int j) { if(i<0 || i>=board.size() || j<0 || j>=board[0].size()) return false; for(int ni=0;ni<board.size();++ni) { if(ni == i || board[ni][j] == ‘.‘) continue; if(board[ni][j] == board[i][j]) return false; } for(int nj=0;nj<board[0].size();++nj) { if(nj == j || board[i][nj] == ‘.‘) continue; if(board[i][nj] == board[i][j]) return false; } return true; } bool checkLocal(vector<vector<char>>& board, int i, int j) { if(i<0 || i>=board.size() || j<0 || j>=board[0].size()) return false; vector<int> idx = getIdx(i, j); int li = idx[0], ri = idx[1], lj = idx[2], rj = idx[3]; for(int p=li;p<=ri;++p) { for(int q=lj;q<=rj;++q) { if((i==p && j==q) || board[p][q] == ‘.‘) continue; if(board[i][j] == board[p][q]) return false; } } return true; } bool isValidSudoku(vector<vector<char>>& board) { for(int i=0;i<board.size();++i) { for(int j=0;j<board[i].size();++j) { if(board[i][j] == ‘.‘) continue; if(!checkLocal(board, i, j) || !checkRowAndColumn(board, i, j)) return false; } } return true; } };
时间: 2024-10-13 16:07:51