https://leetcode.com/problems/valid-sudoku/
Valid Sudoku - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
생각
2차원 배열 형태로 스도쿠의 정보가 주어졌을때, 올바른 스도쿠인지 판단하는 문제입니다.
숫자가 없는 칸이 존재하기때문에 올바른 스도쿠인지 판단하기 위해 다음과 같이 확인하였습니다.
1. 가로방향 1~9가 중복되었는지 체크한다.
2. 세로방향 1~9가 중복되었는지 체크한다.
3. 3*3 영역에서 1~9가 중복되었는지 체크한다.
중복을 체크하기위해 boolean 1차원 배열을 만들었습니다. 방문 후 true 로 flag를 설정하였기 때문에, 이미 방문한 숫자라면 return false를 시켜주었습니다.
Java Code
class Solution {
public boolean isValidSudoku(char[][] board) {
int R = board.length;
int C = board[0].length;
for(int i=0; i < R; i++){
boolean[] numbers = new boolean[10];
for(int j=0; j < C; j++){
if(board[i][j] != '.'){
if(!numbers[board[i][j]-'0']){
numbers[board[i][j]-'0'] = true;
}else{
return false;
}
}
}
}
for(int i=0; i < C; i++){
boolean[] numbers = new boolean[10];
for(int j=0; j < R; j++){
if(board[j][i] != '.'){
if(!numbers[board[j][i]-'0']){
numbers[board[j][i]-'0'] = true;
}else{
return false;
}
}
}
}
//3*3 영역 합 계산
for (int i = 0; i < 9; i+=3) {
for (int j = 0; j < 9; j+=3) {
if(!areaCalc(i,j,board)) return false;
}
}
return true;
}
public boolean areaCalc(int y, int x, char[][] board) {
boolean[] numbers = new boolean[10];
for (int i = y; i < y+3; i++) {
for (int j = x; j < x+3; j++) {
if(board[i][j] != '.') {
if(!numbers[board[i][j]-'0']){
numbers[board[i][j]-'0'] = true;
}else{
return false;
}
}
}
}
return true;
}
}
'Algorithm' 카테고리의 다른 글
[LeetCode] Python - 207. Course Schedule (0) | 2021.07.09 |
---|---|
[LeetCode] Java, Python - 743. Network Delay Time (0) | 2021.07.07 |
[LeetCode] Python - 129. Sum Root to Leaf Numbers (0) | 2021.07.06 |
[LeetCode] Python - 100. Same Tree (0) | 2021.07.06 |
[LeetCode] Python - 102. Binary Tree Level Order Traversal (0) | 2021.07.04 |