[LeetCode] 112: Sudoku Solver

来源:互联网 发布:mac图片文件夹在哪里 编辑:程序博客网 时间:2024/06/05 05:53
[Problem]

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.

[LeetCode] 112: Sudoku Solver - coder007 - Coder007的博客

A sudoku puzzle...

[LeetCode] 112: Sudoku Solver - coder007 - Coder007的博客

...and its solution numbers marked in red.


[Solution]

class Solution {
public:
/**
* DFS
*/
bool DFS(vector<vector<char> > &board, vector<pair<int, int> > unSolve, bool rowUsed[9][10], bool columnUsed[9][10], bool cubeUsed[9][10]){
if(unSolve.size() == 0)return true;

// the last one
if(unSolve.size() == 1){
int i = unSolve[0].first;
int j = unSolve[0].second;

// get the unused number in the row i
int k = 1;
for(k = 1; k <= 9; ++k){
if(!rowUsed[i][k])break;
}

// there is no unused number in the row i, or the number is used in the column j or the cube (i/3)*3+j/3
if(k == 10 || columnUsed[j][k] || cubeUsed[(i/3)*3+j/3][k])return false;

// success
board[i][j] = k + '0';
return true;
}
else{
int i = unSolve[0].first;
int j = unSolve[0].second;

// get the unused number in the row i
for(int k = 1; k <= 9; ++k){
// both the row i, the column j and the cube (i/3)*3+j/3 not use k
if(rowUsed[i][k] || columnUsed[j][k] || cubeUsed[(i/3)*3+j/3][k])continue;

// set the used
rowUsed[i][k] = columnUsed[j][k] = cubeUsed[(i/3)*3+j/3][k] = true;

// set the board
board[i][j] = k + '0';

// remove a pair from unSolve
unSolve.erase(unSolve.begin());

// solved
if(DFS(board, unSolve, rowUsed, columnUsed, cubeUsed)){
return true;
}

// unsolved, reset the marks
rowUsed[i][k] = columnUsed[j][k] = cubeUsed[(i/3)*3+j/3][k] = false;
board[i][j] = '.';
unSolve.insert(unSolve.begin(), pair<int, int>(i, j));
}
}
return false;
}
/**
* solve Sudoku
*/
void solveSudoku(vector<vector<char> > &board) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// initial
vector<pair<int, int> > unSolve;
bool rowUsed[9][10], columnUsed[9][10], cubeUsed[9][10];// 9 rows, 9 columns, 9 cubes
memset(rowUsed, 0, sizeof(rowUsed));
memset(columnUsed, 0, sizeof(columnUsed));
memset(cubeUsed, 0, sizeof(cubeUsed));
for(int i = 0; i < 9; ++i){
for(int j = 0; j < 9; ++j){
if(board[i][j] != '.'){
rowUsed[i][board[i][j]-'0'] = true;
columnUsed[j][board[i][j]-'0'] = true;
cubeUsed[(i/3)*3+j/3][board[i][j]-'0'] = true;
}
else{
unSolve.push_back(pair<int, int>(i, j));
}
}
}

// DFS
DFS(board, unSolve, rowUsed, columnUsed, cubeUsed);
}
};

说明:版权所有,转载请注明出处。Coder007的博客