Easy to understand C# solution (using list)


  • 0
    K
    public class Solution {
        public bool IsValidSudoku(char[,] board) {
            
            List<char> list = new List<char>();
            List<char> listRow = new List<char>();
            List<char> listCol = new List<char>();
    
            //check 9 rows and columns
            for (int i=0;i<9;i++)        
            {
                for (int j=0;j<9;j++)
                {
                    if (board[i,j] != '.') 
                    {
                        if (listRow.Contains(board[i,j]))
                            return false;
                        else
                            listRow.Add(board[i,j]);
                    }
                    if (board[j,i] != '.') 
                    {
                        if (listCol.Contains(board[j,i]))
                            return false;
                        else
                            listCol.Add(board[j,i]);
                    }
                }
                listRow.Clear();  
                listCol.Clear(); 
            }
            //check 9 sub-boxes
            for (int i=0;i<9;i+=3)
            {
                for (int j=0;j<9;j+=3)
                {
                    for (int k=0;k<3;k++)
                    {
                        for (int m=0;m<3;m++)
                        {
                            if (board[k+i,j+m] != '.') 
                            {
                                if (list.Contains(board[k+i,j+m]))
                                    return false;
                                else
                                    list.Add(board[k+i,j+m]);
                            }
                        }
                    }
                    list.Clear();
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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