标签:style http color os io ar for div 问题
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.
题意:填充数独,返回是否填充成功
思路:dfs
找一个还没填充的位置,尝试填写0-9其中的一个数字,判断是否理。
如果合理,则可以转移到一个同样子问题,所以可以采用递归的方式实现。
bool solveSudoku(vector<vector<char> >&board)
返回是否成功填充当前状态为 board的数独
bool isValid(const vector<vector<char> >&board, int x, int y){ //检查行 for(int j = 0; j < 9; ++j) if(j != y && board[x][j] == board[x][y]) return false; //检查列 for(int i = 0; i < 9; ++i) if(i != x && board[i][y] == board[x][y]) return false; //检查小方块 for(int i = 0; i < 3; ++i) for(int j = 0; j < 3; ++j){ if(!(x/3 * 3 + i == x && y /3 * 3 + j == y) && board[x/3 * 3 + i][y /3 * 3 + 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 = 0; k < 9; ++k){ board[i][j] = k + '1' ; if(isValid(board, i, j) && solveSudoku(board)) return true; board[i][j] = '.'; } return false; } } } return true; //漏写了这句,WA了好多次 }
标签:style http color os io ar for div 问题
原文地址:http://blog.csdn.net/zhengsenlie/article/details/39119261