Leetcode/Top Interview 150
[Matrix][Medium] 36. Valid Sudoku
자전거통학
2024. 5. 4. 00:49
https://leetcode.com/problems/valid-sudoku/description
Q. 유효한 sudoku인지 판단하라.
Solution
위 3 조건을 체크하는 로직을 만든다.
다양한 방법이 있을 수 있다고 본다.
최대한 간단하게 만들어 본다.
더보기
bool IsValid(char ch, HashSet<char> cache)
{
if(ch<'0' || ch>'9')
return false;
if(cache.Contains(ch))
return false;
return true;
}
public bool IsValidSudoku(char[][] board)
{
// Row check.
for(int y = 0; y < board.Length; ++y)
{
HashSet<char> buff = new HashSet<char>();
for(int x = 0; x < board[0].Length; ++x)
{
char cur = board[y][x];
if(cur == '.') continue;
if(!IsValid(cur, buff))
return false;
buff.Add(board[y][x]);
}
}
// Col check.
for(int x = 0; x < board[0].Length; ++x)
{
HashSet<char> buff = new HashSet<char>();
for(int y = 0; y < board.Length; ++y)
{
char cur = board[y][x];
if(cur == '.') continue;
if(!IsValid(cur, buff))
return false;
buff.Add(board[y][x]);
}
}
// 3x3 box check.
for(int iY = 0; iY < 9; iY += 3)
{
for(int iX = 0; iX < 9; iX += 3)
{
HashSet<char> buff = new HashSet<char>();
for(int y = 0; y < 3; ++y)
{
for(int x = 0; x < 3; ++x)
{
char cur = board[y+iY][x+iX];
if(cur == '.') continue;
// Console.WriteLine(cur);
if(!IsValid(cur, buff))
return false;
buff.Add(cur);
}
}
Console.WriteLine("");
}
}
return true;
}
결과.