您的位置:首页 > 编程语言 > C语言/C++

LeetCode 37. Sudoku Solver--回溯法

2017-11-07 19:10 495 查看
题目链接

37. Sudoku Solver

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.



A sudoku puzzle...



...and its solution numbers marked in red.

解:其实和八皇后的问题是类似的,只是状态和判断冲突复杂了一些,首先要清楚数独的规则,每一行每一列是1~9,每个小九宫格是1~9,(注意对角线不一定是1~9!!),从左上角的位置开始向右向下填,遇到数字直接跳过,当在某个位置没有数字可填时,回溯,注意在回溯过程中要把已经填的数字都恢复到
‘.’ 原状态,当填到右下角的位置,且那个位置是固定数字or可以找到一个不冲突的数字填入,说明找到了解,代码:

class Solution {
public:
bool isConflict(int line, int col, char value, vector<vector<char> >& board) {
for (int i = 0; i < 9; i++) {
if (board[i][col] == value) return true;
if (board[line][i] == value) return true;
}
int line_no = line/3;
int col_no = col/3;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (board[line_no*3+i][col_no*3+j] == value) return true;
return false;
}

bool solveOneStep(int line, int col, vector<vector<char> >& board) {
if (board[line][col] != '.') {
if (col == 8 && line == 8) return true;
if (col == 8) return solveOneStep(line+1, 0, board);
else return solveOneStep(line, col+1, board);
}
bool result = false;
for (int i = 1; i <= 9; i++) {
board[line][col] = '.';
if (!isConflict(line, col, '0'+i, board)) {
board[line][col] = '0'+i;
if (line == 8 && col == 8) return true;
if (col == 8) result = solveOneStep(line+1, 0, board);
else result = solveOneStep(line, col+1, board);
if (result) break;
}
}
if (!result) board[line][col] = '.';
return result;
}

void solveSudoku(vector<vector<char> >& board) {
solveOneStep(0, 0, board);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数独 c++ 回溯 LeetCode