반응형
36. Valid Sudoku
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 nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentioned rule
Example 1:
Input: board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true
Example 2:
Input: board =
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
계획
문제 해결 전략
가로 체크 : board[i][j]
세로 체크 : board[j][i]
박스 체크: board[3*Math.floor(i/3)+Math.floor(j/3)][3*(i%3)+(j%3)]
구현 전략
위에 식대로 O(N^2)속도로 3가지 방법으로 스도쿠가 valid인지 확인합니다. 새로운값을 찾을때마다,
해설
var isValidSudoku = function(board) {
for (let i = 0; i < 9; i++) {
let row = new Set(),
col = new Set(),
box = new Set();
for (let j = 0; j < 9; j++) {
let _row = board[i][j];
let _col = board[j][i];
let _box = board[3*Math.floor(i/3)+Math.floor(j/3)][3*(i%3)+(j%3)]
if (_row != '.') {
//빈값이아니면서, 이미 있던 값이면, return false invailid sudoku
if (row.has(_row)) return false;
//처음 발견한 값이면, _row를 추가
row.add(_row); //세트에 추가
}
if (_col != '.') {
if (col.has(_col)) return false;
col.add(_col);
}
if (_box != '.') {
if (box.has(_box)) return false;
box.add(_box);
}
}
}
//끝까지 loop가 false없이 돌았다면 true리턴 valid sudoku인게 인증됨
return true
};
반응형
'개발공부 > LeetCode' 카테고리의 다른 글
[JavaScript] 991. Broken Calculator 쉬운 설명 (0) | 2022.03.24 |
---|---|
[Javascript] 1663. Smallest String With A Given Numeric Value -쉬운 설명 (0) | 2022.03.22 |
[JavaScript] 49. Group Anagrams 쉬운설명, hasmap사용 (0) | 2022.03.20 |
[JavaScript] 33. Search in Rotated Sorted Array - 쉬운설명 바이너리 서치 활용 (0) | 2022.03.19 |
[JavaScript]856. Score of Parentheses 쉬운설명, stack 사용 (0) | 2022.03.17 |