leetcode #37 in cpp

来源:互联网 发布:php学生管理系统 编辑:程序博客网 时间:2024/06/03 12:27

The question is to solve a Sudoku.

Solution:

We scan through the Sudoku. Whenever we meet a '.', we try  to fill it 1 to 9. Every time we fill in a number, first check if this number could be put without any collisions, second check if this number would result in future collisions. Either violation would force us to try other characters. So this leads us to a recurrent structure: 

int solve(sudoku){<span style="white-space:pre"></span>for each cell in sudoku == '.':
<span style="white-space:pre"></span>for i = 1 to 9:current cell <- 'i'if sudoku is valid: <span style="white-space:pre"></span>if solve(sudoku) == 1://no future collision in next recurrent callsreturn true<span style="white-space:pre"></span>end for<span style="white-space:pre"></span>current cell <---'.'//no characters fit, which means a collision happens against some cells in previous recurrence.<span style="white-space:pre"></span>return false//perform back-track.<span style="white-space:pre"></span>end for<span style="white-space:pre"></span>return true;}

Code: 

class Solution {public:    void solveSudoku(vector<vector<char>>& board) {        solve(board);    }    int solve(vector<vector<char>>& board){        for(int r = 0; r < 9; r ++){            for(int c = 0; c < 9; c++){                if(board[r][c] != '.') continue;                for(int i = 0; i < 9; i ++){//list all possible numbers                    if(isValidSudoku(board,r,c,'1' + i)){//check if we can put this number                        board[r][c] = '1' + i;                        if(solve(board))//check if this number results in no future collisions.                            return 1;                    }                }                board[r][c] = '.';                return false;//if all characters are tried but none succeeded, perform back-track.            }        }        return 1;    }    bool isValidSudoku(vector<vector<char>> board,int r, int c,char ch) {        int col_lower = (c/3) * 3;        int row_lower = (r/3) * 3;        for(int k = 0; k < 9; k ++){            if(board[r][k] == ch || board[k][c] == ch || board[row_lower + k/3][col_lower + k%3] == ch) return false;         }              return true;    }    };


0 0
原创粉丝点击