题解 | #Sudoku#
Sudoku
https://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1
#include <iostream>
#include <vector>
using namespace std;
const int n = 9;
vector<vector<int>> mp(9, vector<int>(9)) ;
bool isEnd = false;
bool check(int row, int col, int val) {
for (int i = 0; i < n; i++) {
if (val == mp[i][col]) {
return false;
}
}
for (int i = 0; i < n; i++) {
if (val == mp[row][i]) {
return false;
}
}
int limit_row = row / 3 * 3 + 3;
int limit_col = col / 3 * 3 + 3;
for (int i = limit_row - 3; i < limit_row; i++) {
for (int j = limit_col - 3; j < limit_col; j++) {
if (val == mp[i][j]) {
return false;
}
}
}
return true;
}
void dfs(int row, int col) {
if (col == 9) {
row++;
col = 0;
}
if (row == 9) {
isEnd = true;
return ;
}
if (mp[row][col] == 0) {
for (int i = 1; i <= n; i++) {
if (check(row, col, i)) {
mp[row][col] = i;
dfs(row, col + 1);
if (isEnd == true) {
return ;
}
mp[row][col] = 0;
}
}
} else {
dfs(row, col + 1);
}
}
int main() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cin >> mp[i][j];
}
}
dfs(0, 0);
for (auto& i : mp) {
for (auto& j : i) {
cout << j << ' ';
}
cout << endl;
}
}
// 64 位输出请用 printf("%lld")

顺丰集团工作强度 382人发布