LeetCode-Sudoku Solver
2013-10-04 16:16
225 查看
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.
View Code
Empty cells are indicated by the character
'.'.
You may assume that there will be only one unique solution.
class Solution { public: void solveSudoku(vector<vector<char> > &board) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<bool> >check; vector<bool> one; one.resize(9,false); check.resize(27,one); vector<vector<int> > empty; for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ int val=board[i][j]-'1'; if(val>=0&&val<9){ check[i][val]=true; check[9+j][val]=true; check[18+(i/3)*3+j/3][val]=true; } else{ int size=empty.size(); empty.resize(size+1); empty[size].push_back(i); empty[size].push_back(j); empty[size].push_back(0); } } } int index=0; while(true){ int val=empty[index][2]; int i=empty[index][0]; int j=empty[index][1]; if(val==9){ //go back index--; val=empty[index][2]; i=empty[index][0]; j=empty[index][1]; check[i][val]=false; check[9+j][val]=false; check[18+(i/3)*3+j/3][val]=false; empty[index][2]++; } else{ if(check[i][val]||check[9+j][val]||check[18+(i/3)*3+j/3][val]){ //try next val empty[index][2]++; } else{ check[i][val]=true; check[9+j][val]=true; check[18+(i/3)*3+j/3][val]=true; index++; if(index==empty.size()){ //end for(int k=0;k<empty.size();k++){ board[empty[k][0]][empty[k][1]]='1'+empty[k][2]; } return; } empty[index][2]=0; } } } } };
View Code
相关文章推荐
- Sudoku Solver - Leetcode
- [Leetcode 103] 37 Sudoku Solver
- LeetCode 37.Sudoku Solver
- leetcode--Sudoku Solver
- LeetCode 37 Sudoku Solver 回溯和深度遍历 还要学习
- leetcode 37 sudoku solver
- LeetCode-----37. Sudoku Solver(解数读)
- LeetCode-37-Sudoku Solver, list转字符串join,回溯
- leetcode Sudoku Solver
- 【leetcode】Sudoku Solver
- [LeetCode] Sudoku Solver
- leetcode:Sudoku Solver
- 【LeetCode】Sudoku Solver
- LeetCode解题报告—— Reverse Nodes in k-Group && Sudoku Solver
- [leetcode] 37. Sudoku Solver
- [Leetcode] Sudoku Solver
- LeetCode | Sudoku Solver
- Sudoku Solver 破解数独 @LeetCode 附DFS感想
- leetcode题解c++ | 37. Sudoku Solver
- 【Leetcode】【python】Sudoku Solver