Leetcode keeps throwing runtime error for valid sudoku


  • 0
    N

    Hello,

    Below is my code for Valid Sudoku:

    class Solution {
    public:
        bool isValidRowSudoku(vector<vector<char> > &board){
            bool *flag = new bool[9];
            int i, j;
            for( i=0; i<9; i++){
                memset(flag, 0 , sizeof(bool)*9);
                if( board[i].size() != 9 )
                    return false;
                for( j=0; j<9; j++){
                    if( board[i][j] == '.' ) continue;
                    if( board[i][j] < '1' || board[i][j] > '9')
                        return false;
                    if( !flag[board[i][j] - '1'] )
                        flag[board[i][j]-'1'] = true;
                    else{
                        delete[] flag;
                        return false;
                    }
                }
            }
            delete[] flag;
            return true;
        }
        
        bool isValidColumnSudoku(vector<vector<char> > &board){
            bool *flag = new bool[9];
            int i, j;
            for( i=0; i<9; i++){
                memset(flag, 0 , sizeof(bool)*9);
                for( j=0; j<9; j++){
                    if( board[i][j] == '.' ) continue;
                    if( !flag[board[j][i] - '1'] )
                        flag[board[j][i]-'1'] = true;
                    else{
                        delete[] flag;
                        return false;
                    }
                }
            }
            delete[] flag;
            return true;
        }
        
        bool isValidSudoku(vector<vector<char> > &board) {
            if( board.size() != 9 )
                return false;
            return isValidRowSudoku(board) && isValidColumnSudoku(board);
        }
    };
    

    However i keep getting runtime error for the following input:

    ["..5.....6","....14...",".........",".....92..","5....2...",".......3.","...54....","3.....42.","...27.6.."]

    What is going wrong here?


  • 1
    S

    In the second function:

    if( board[i][j] == '.' ) continue;
    

    should really be board[j][i];

    Besides, dynamically creating a boolean array is really pointless here, since the size of the array is a constant. Defining an array on stack would make your life much easier.

    There is another big problem with your code though: You also need a third function to check every 3x3 squares to make sure there are no duplicates in the squares.


Log in to reply
 

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