Study/Algorithm
LeetCode (C/C++) 36. Valid Sudoku
hwooo
2024. 5. 29. 14:46
https://leetcode.com/problems/valid-sudoku/description/
풀이
표를 순회하며 주어진 조건들을 만족하는지 확인한다.
코드
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
bool checkRow[10], checkCol[10];
bool checkBox[3][3][10] = {false, };
for (int i = 0; i < 9; i++) {
fill(checkRow, checkRow + 10, false);
fill(checkCol, checkCol + 10, false);
for (int j = 0; j < 9; j++) {
// check row
if (board[i][j] != '.') {
int numRow = board[i][j] - '0';
if (checkRow[numRow])
return false;
checkRow[numRow] = true;
// check Box
if (i <= j && checkBox[i / 3][j / 3][numRow])
return false;
checkBox[i / 3][j / 3][numRow] = true;
}
// check column
if (board[j][i] != '.') {
int numCol = board[j][i] - '0';
if (checkCol[numCol])
return false;
checkCol[numCol] = true;
// check Box
if (i == j)
continue;
if (i <= j && checkBox[j / 3][i / 3][numCol])
return false;
checkBox[j / 3][i / 3][numCol] = true;
}
}
}
return true;
}