[LeetCode] Sudoku Solver

来源:互联网 发布:微信小游戏源码 编辑:程序博客网 时间:2024/06/06 06:56

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:    bool isVaild(vector<vector<char> > &board,int a,int b){        for(int row = 0;row < 9;row ++){            if(row != a && board[a][b] == board[row][b])                return false;        }        for(int column = 0;column < 9;column ++){            if(column != b && board[a][b] == board[a][column])                return false;        }        int x = (a/3)*3 ,y = (b/3)*3;        for(int i = 0;i < 3;i ++){            for(int j = 0;j < 3;j ++){                if(x + i!= a && y + j!= b && board[a][b] == board[x + i][y + j])                    return false;            }        }        return true;    }        bool generate(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] = k + '0';                        if(isVaild(board, i, j) && generate(board))                            return true;                        board[i][j] = '.';                    }                    return false;                }            }        }        return true;    }    void solveSudoku(vector<vector<char> > &board) {        generate(board);    }};


0 0
原创粉丝点击