标签:ids blog nbsp board sudoku cto tor solution for
方法:采用递归的方式
class Solution { public: void solveSudoku(vector<vector<char>>& board) { solve(board); } bool solve(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=0; k<9; ++k) { board[i][j] = k + ‘1‘; if(isValid(board, i, j) && solve(board)) return true; board[i][j] = ‘.‘; } return false; } } } return true; } bool isValid(vector<vector<char>> &board, int i, int j) { for(int k=0; k<9; ++k) if(i != k && board[i][j] == board[k][j]) return false; for(int k=0; k<9; ++k) if(j != k && board[i][j] == board[i][k]) return false; for(int m=3*(i/3); m<3*(i/3+1); ++m) for(int n=3*(j/3); n<3*(j/3+1); ++n) if(!(i == m && j == n) && board[i][j] == board[m][n]) return false; return true; } };
Valid Sudoku
判别方法同上
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { for(int i=0; i<9; ++i) for(int j=0; j<9; ++j) if(board[i][j] != ‘.‘ && !isValid(board, i, j)) return false; return true; } bool isValid(vector<vector<char>> &board, int i, int j) { for(int k=0; k<9; ++k) if(i != k && board[i][j] == board[k][j]) return false; for(int k=0; k<9; ++k) if(j != k && board[i][j] == board[i][k]) return false; for(int m = 3*(i/3); m<3*(i/3+1); ++m) for(int n = 3*(j/3); n<3*(j/3+1); ++n) if(!(m == i && n == j) && board[i][j] == board[m][n]) return false; return true; } };
标签:ids blog nbsp board sudoku cto tor solution for
原文地址:http://www.cnblogs.com/chengyuz/p/6979261.html