[LeetCode37]Soduko 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.

The idea is straight forward, put the number in empty place. and check if it is valid and solverable. 

Java

public boolean solveSudoku(char[][] board) {
		for(int i=0;i<9;i++){
			for(int j = 0;j<9;j++){
				if(board[i][j]=='.'){
					for(int k=1;k<=9;k++){
						board[i][j]=(char) (k+48);
						if(validSudoku(board, i, j) && solveSudoku(board) )
							return true;
						board[i][j] = '.';
					}
					return false;
				}
			}
		}
		return true;
    }
	public boolean validSudoku(char[][] board, int x, int y){
		for(int i=0;i<9;i++){
			if(i!=x && board[i][y]==board[x][y])
				return false;
			if(i!=y && board[x][i]==board[x][y])
				return false;
		}
		for(int i=3*(x/3);i<3*(x/3+1);i++){
			for(int j=3*(y/3);j<3*(y/3+1);j++){
				if(i!=x && j!=y && board[i][j] == board[x][y])
					return false;
			}
		}
		return true;
	}
c++

bool isValidSudoku2(vector<vector<char>> &board, int x,int y){
    int i, j;
    for(i=0; i<9; i++)
        if(i!= x && board[i][y] == board[x][y])
            return false;
    for(j = 0; j<9; j++)
        if(j!= y && board[x][j] == board[x][y])
            return false;
    for(i = 3*(x/3); i<3*(x/3+1); i++){
        for(j = 3 *(y/3); j<3*(y/3+1);j++)
            if(i!=x && j!= y && board[i][j] == board[x][y])
                return false;
    
    }
    return true;
}
bool solveSudoku(vector<vector<char> > &board) {
    for(int i=0; i<9;i++){
        for(int j=0;j<9;j++){
            if('.' == board[i][j]){
                for(int k=1;k<=9;k++){
                    board[i][j] = '0' + k;
                    if(isValidSudoku2(board,i,j) && solveSudoku(board))
                        return true;
                    board[i][j] = '.';
                }
                return false;
            }
        }
    }
    return true;
}





你可能感兴趣的:(LeetCode,sudoku)