Friday, December 12, 2014

Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.
A sudoku puzzle...


...and its solution numbers marked in red.
 
 
class Solution {
public:
    void solveSudoku(vector<vector<char> > &board) {
        int r=board.size();
        if (r==0) return;
        int c=board[0].size();
        if (c==0) return;
        solve(board,r,c);
   
    }
   
    bool valid(vector<vector<char> > &board,int x, int y, int t,  int r, int c)
    {
        //check col, rows
        for (int i=0; i<r; i++)
        {
            if (board[i][y]==board[x][y]&&i!=x)
                return false;
        }
       
        for (int j=0; j<c; j++)
        {
            if (board[x][j]==board[x][y]&&j!=y)
               return false;
        }
       
        int regionX = (x/3)*3;
        int regionY = (y/3)*3;
       
        for (int i=regionX; i<regionX+3; i++)
        {
            for (int j=regionY; j<regionY+3; j++)
            {
                if (board[i][j]==board[x][y]&&((i!=x)||(j!=y)))
                   return false;
            }
        }
        return true;
    }
   
    bool solve(vector<vector<char> > &board, int r, int c)
    {
        for (int x=0; x<r; x++)
        {
            for (int y=0; y<c; y++)
            {
                if (board[x][y]=='.')
                {
                    for (int i=0; i<9; i++)
                    {
                        board[x][y] = '1'+i;
                        if (valid(board,x,y,i,r,c)&&solve(board,r,c))
                           {
                               return true;
                           }
                        board[x][y]='.';

                    }
                    return false;
                }
            }
        }
        return true;
    }
};

No comments:

Post a Comment