Leetcode Sudoku Solver My Submissions Question
,本问题主要是使用递归的思想,不断的试探,直到得出结果,同时也得注意记录已有值的方法,主要是横向、纵向、以及每上九宫格。相关代码如下:
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
vector<vector<bool> > state_row(9, vector<bool>(10, false));
vector<vector<bool> > state_col(9, vector<bool>(10, false));
vector<vector<bool> > state_cell(9, vector<bool>(10, false));
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
if (board[row][col] != '.') {
int tmp = board[row][col] - '0';
state_row[row][tmp] = true;
state_col[col][tmp] = true;
state_cell[row / 3 *3 + col / 3][tmp] = true;
}
}
}
backtack(state_row, state_col, state_cell, board, 0, 0);
}
bool backtack(vector<vector<bool> >& state_row,
vector<vector<bool> >& state_col,
vector<vector<bool> >& state_cell,
vector<vector<char> >& board,
int row, int col) {
if (row == 9) {
return true;
}
if (col == 9) {
return backtack(state_row, state_col, state_cell,
board, row + 1, 0);
}
if (board[row][col] == '.') {
for (int i = 1; i <= 9; i++) {
if (!state_row[row][i] && !state_col[col][i] &&
!state_cell[row / 3 * 3 + col / 3][i]) {
board[row][col] = '0' + i;
state_row[row][i] = true;
state_col[col][i] = true;
state_cell[row / 3 * 3 + col / 3][i] = true;
bool state = backtack(state_row, state_col, state_cell,
board, row, col + 1);
if (state) {
return true;
}
board[row][col] = '.';
state_row[row][i] = false;
state_col[col][i] = false;
state_cell[row / 3 * 3 + col / 3][i] = false;
}
}
return false;
} else {
return backtack(state_row, state_col, state_cell,
board, row, col + 1);
}
}
};
// Sample input: ./a.out numa_1 numa_2 numb_1 numb_2...
int main(int argc, char * argv[]) {
Solution so;
vector<vector<char> > board(9, vector<char>(9, '.'));
for (int i = 1; i <= 9; i++) {
for (int j = 0; j < 9; j++) {
board[i - 1][j] = argv[i][j];
}
}
cout<<"board: "<<endl;
for (auto a : board) {
for (auto c : a) {
cout<<c<<" ";
}
cout<<endl;
}
cout<<endl;
so.solveSudoku(board);
cout<<"result: "<<endl;
for (auto a : board) {
for (auto c : a) {
cout<<c<<" ";
}
cout<<endl;
}
cout<<endl;
return 0;
}
测试:./a.out ..9748... 7........ .2.1.9... ..7...24. .64.1.59. .98...3.. ...8.3.2. ........6 ...2759..
结果:
board:
. . 9 7 4 8 . . .
7 . . . . . . . .
. 2 . 1 . 9 . . .
. . 7 . . . 2 4 .
. 6 4 . 1 . 5 9 .
. 9 8 . . . 3 . .
. . . 8 . 3 . 2 .
. . . . . . . . 6
. . . 2 7 5 9 . .
result:
5 1 9 7 4 8 6 3 2
7 8 3 6 5 2 4 1 9
4 2 6 1 3 9 8 7 5
3 5 7 9 8 6 2 4 1
2 6 4 3 1 7 5 9 8
1 9 8 5 2 4 3 6 7
9 7 5 8 6 3 1 2 4
8 3 2 4 9 1 7 5 6
6 4 1 2 7 5 9 8 3