题目一:Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character ‘.‘
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
class Solution { public: bool isValidSudoku(vector<vector<char> > &board) { vector<bool> check(9,false); int i,j,block; for(i = 0;i < 9;++i)//判断每一行是否有效 { check.assign(9,false); for(j = 0; j < 9;++j) { if(board[i][j] == '.')continue; if(check[board[i][j] - '0'])return false; check[board[i][j] - '0'] = true; } } for(i = 0;i < 9;++i)//判断每一列是否有效 { check.assign(9,false); for(j = 0;j < 9;++j) { if(board[j][i] == '.')continue; if(check[board[j][i] - '0'])return false; check[board[j][i] - '0'] = true; } } for(block = 0;block < 9;++block)//判断每一块是否有效 { int startx = (block/3)*3;//选择每一块的开始位置 int starty = (block%3)*3; check.assign(9,false); for(i = startx; i < startx+3;++i) { for(j = starty;j < starty+3;++j) { if(board[i][j] == '.')continue; if(check[board[i][j] - '0'])return false; check[board[i][j] - '0'] = true; } } } return true; } };
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.
思路:递归测试每一个空白点是否有效,和n皇后类似class Solution { public: bool check_valid(vector<vector<char> >& board,int row,int col) { int i,j; for(i = 0;i < 9;++i)//判断该行是否有效 { if(i != col && board[row][i] == board[row][col])return false; } for(i = 0;i < 9;++i)//判断该列是否有效 { if(i != row && board[i][col] == board[row][col])return false; } for(i = (row / 3)*3;i < (row /3 +1)*3;++i)//判断该块是否有效 { for(j = (col / 3)*3;j < (col / 3+1)*3;++j) { if(i != row && j != col && board[i][j] == board[row][col])return false; } } return true; } bool isValidSudoku(vector<vector<char> >& board) { int row,col; for(row = 0;row < 9;++row) { for(col = 0;col < 9;++col) { if(board[row][col] == '.') { int i; for(i = 1;i <= 9;++i)//测试每一个数字是否有效 { board[row][col] = i + '0'; if(check_valid(board,row,col) && isValidSudoku(board))return true; } board[row][col] = '.'; return false; } } } return true; } void solveSudoku(vector<vector<char> > &board) { isValidSudoku(board); } };
Valid Sudoku 和 Sudoku Solver,布布扣,bubuko.com
原文地址:http://blog.csdn.net/fangjian1204/article/details/38515747