My Concise C# Solution


  • 0
    D

    public class Solution {
       public bool IsValidSudoku(char[,] board) {
          const int numberOfCols = 9;
          const int squareLength = 3;
          const int numberOfRows = numberOfCols;
          bool isValid = true;
    
          for (int i=0; i < numberOfCols && isValid; i++) {
             HashSet<char> xSet = new HashSet<char> ();
             HashSet<char> ySet = new HashSet<char> ();
             HashSet<char> squareSet = new HashSet<char> ();
    
             for (int j=0; j < numberOfRows; j++) {
                //Check squares
                //Row positions slowly increase
                int rowOffset = squareLength * (i / squareLength);
                int rowPosition = rowOffset + j / squareLength;
                //Column positions cycle 
                int columnOffset = (i % squareLength) * squareLength;
                int columnPosition = columnOffset + j % squareLength;
                if (board [rowPosition, columnPosition] != '.'){
                   if (!squareSet.Add (board [rowPosition, columnPosition])){
                      isValid = false;
                      break;
                   } 
                }
                
                //Check row
                if (board [i, j] != '.') {
                   if (!xSet.Add (board [i, j])) {
                      isValid = false;
                      break;
                   } 
                } 
                
                //Check column
                if (board [j, i] != '.') {
                   if (!ySet.Add (board [j, i])) {
                      isValid = false;
                      break;
                   } 
                }
             }
          }
    
          return isValid;
       }
    }
    


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.