Skip to content

Instantly share code, notes, and snippets.

@svaza
Created April 27, 2022 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svaza/c1ca0c3afe52f04a37af9e022dfa7fa6 to your computer and use it in GitHub Desktop.
Save svaza/c1ca0c3afe52f04a37af9e022dfa7fa6 to your computer and use it in GitHub Desktop.
Valid Sudoku
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public bool IsValidSudoku(char[][] board) {
List<List<HashSet<int>>> sudokuSection = Enumerable.Range(1, 3)
.Select(x => Enumerable.Range(1, 3).Select(x1 => new HashSet<int>(9)).ToList()).ToList();
List<HashSet<int>> rows = Enumerable.Range(1, 9).Select(x => new HashSet<int>(9)).ToList();
List<HashSet<int>> columns = Enumerable.Range(1, 9).Select(x => new HashSet<int>(9)).ToList();
for(int r = 0; r < 9; r++)
{
for(int c = 0; c < 9; c++)
{
if(board[r][c] == '.') continue;
var currentNum = board[r][c] - '0';
if(currentNum >= 1 && currentNum <= 9)
{
if(!rows[r].Add(currentNum)) return false;
if(!columns[c].Add(currentNum)) return false;
if(!sudokuSection[r/3][c/3].Add(currentNum)) return false;
}
else
{
return false;
}
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment