标签:style blog color io for ar div amp
思路:
dfs+数独游戏规则。
数独游戏规则是:
同行同列不能有重复数字;并且每9宫内不能有重复数字
1 class Solution { 2 public: 3 bool isValid(vector<vector<char> > &board, int a, int b) { 4 int i,j; 5 for(i = 0; i < 9; i++) 6 if(i != a && board[i][b] == board[a][b]) 7 return false; 8 9 for(j = 0; j < 9; j++) 10 if(j != b && board[a][j] == board[a][b]) 11 return false; 12 13 int x = a/3*3; 14 int y = b/3*3; 15 for(i = 0; i < 3; i++) 16 for(j = 0; j< 3; j++) 17 if(x+i != a && y+j != b && board[x+i][y+j] == board[a][b]) 18 return false; 19 return true; 20 } 21 bool solveSudokudfs(vector<vector<char> > &board) 22 { 23 for(int i = 0; i < 9; i++) 24 for(int j = 0; j < 9; j++) 25 { 26 if(board[i][j] == ‘.‘) 27 { 28 for(int k = 1; k <= 9; k++) 29 { 30 board[i][j] = ‘0‘ + k; 31 if(isValid(board,i,j) && solveSudokudfs(board)) 32 return true; 33 board[i][j] = ‘.‘; 34 } 35 return false; 36 } 37 } 38 return true; 39 } 40 void solveSudoku(vector<vector<char> > &board) { 41 // Note: The Solution object is instantiated only once. 42 solveSudokudfs(board); 43 } 44 };
LeetCode--Sudoku Solver,布布扣,bubuko.com
标签:style blog color io for ar div amp
原文地址:http://www.cnblogs.com/cane/p/3903435.html