forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudoku_Solver.cpp
More file actions
89 lines (77 loc) · 1.73 KB
/
Sudoku_Solver.cpp
File metadata and controls
89 lines (77 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 26, 2012
Problem: Sudoku Solver
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
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.
Solution:
dfs
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
#include <list>
#include <fstream>
using namespace std;
class Solution {
public:
bool recursion(vector<vector<char> > &board, list<int> &blank) {
if (blank.empty()) {
return true;
}
int cell = blank.front();
int x = cell / 9, y = cell % 9;
bool available[10];
for (int i = 1; i <= 9; i++) {
available[i] = true;
}
for (int i = 0; i < 9; i++) {
if (board[i][y] != '.') {
available[board[i][y] - '0'] = false;
}
if (board[x][i] != '.') {
available[board[x][i] - '0'] = false;
}
}
for (int i = 0, mx = x / 3 * 3, my = y / 3 * 3; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[mx + i][my + j] != '.') {
available[board[mx + i][my + j] - '0'] = false;
}
}
}
for (int i = 1; i <= 9; i++) {
if (available[i]) {
blank.pop_front();
board[x][y] = '0' + i;
if (recursion(board, blank)) {
return true;
}
blank.push_front(cell);
board[x][y] = '.';
}
}
return false;
}
void solveSudoku(vector<vector<char> > &board) {
list<int> blank;
for (int i = 0, count = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
blank.push_back(count);
}
count++;
}
}
recursion(board, blank);
}
};