LeetCode 37. Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

The '.' character indicates empty cells.

Example 1:

Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
Explanation: The input board is shown above and the only valid solution is shown below:

Constraints:

board.length == 9
board[i].length == 9
board[i][j] is a digit or '.'.
It is guaranteed that the input board has only one solution.

实现思路:

这道题很有难度,比起N皇后问题要更加地复杂,本题采用两种方法去实现,一种采用双重循环+dfs回溯剪枝的方式,一种采用N-皇后问题的单重循环回溯算法的解决方式去做,先来思考一些N-皇后问题,如果是N-皇后问题中,9X9的棋盘格子中,因为固定了皇后都放在不同一行,只需要根据皇后放置在不同列的情况进行穷举,并且皇后这个数字是唯一的'Q'字符,所以采用了for循环中进行dfs的一个单循环回溯算法方式,但本题数独的问题中,这个数字变量是大大提高了的,首先数字可以放在不同行不同列,并且一个坐标上可以放的数字又是1-9,所以情况就变多了,这里第一种答题的回溯模式,就是三重循环+dfs回溯,本题需要注意只需要给出一组答案即可,剩余答案需要进行剪枝操作,题目要求是按照行优先从1-9循环给数求数独答案的方式,求出这一组解即可。
先给出回溯图的一小部分,这里引用leetcode题解代码随想录作者的图

AC代码:

方法一:

采用三重循环+dfs回溯的方式

class Solution {
		bool judge(int row,int col,char c,vector<vector<char>> &board) {
			for(int i=0; i<board.size(); i++)
				if(board[row][i]==c) return false;//一行上是否有相同元素
			for(int j=0; j<9; j++)
				if(board[j][col]==c) return false;//一列上是否存在相同元素
			//判断在一个小方格内是否有元素重复
			int _row=(row/3)*3;//找出处于第几个大方格   9个9宫格
			int _col=(col/3)*3;
			for(int i=_row; i<_row+3; i++) {
				for(int j=_col; j<_col+3; j++) {
					if(board[i][j]==c) return false;//九宫格内是否有相同元素
				}
			}
			return true;//可以放置元素
		}

		bool dfs(vector<vector<char>> &board) {
			for(int x=0; x<9; x++) {
				for(int y=0; y<9; y++) {
					if(board[x][y]!='.') continue;
					for(char u='1'; u<='9'; u++) {
						if(judge(x,y,u,board)) {//是个合适的放元素的位置
							board[x][y]=u;//放下元素
                                //找到合适的一组后直接要返回了 不需要继续找了 剪枝
							if(dfs(board)) return true;
							board[x][y]='.';//回溯
						}
					}
					return false;//这句语句很关键 当1~9都不能放到当前小方格时不合法
				}
			}
			return true;//说明最终返回了确认的位置
		}

	public:
		void solveSudoku(vector<vector<char>>& board) {
			dfs(board);
		}
};

方法二:

办法二是将本题的棋盘抽象成类似N-皇后问题的解答方式,将每一个坐标(x,y)抽象成一个方格,用三个数组来判断行列和九宫格内数是否重复的方法,巧妙利用空间换时间,所以方法二的效率达到100%,远远比方法一要好。

class Solution {
   private:
   	bool line[9][9]= {0};//利用数组存储某行存数的情况
   	bool column[9][9]= {0};
   	bool block[3][3][9]= {0};
   	bool valid=false;//当获得一个合法的数独解时为true
   	vector<pair<int, int>> spaces;//用来存放一个个格子的坐标(x,y)

   public:
   	void dfs(vector<vector<char>>& board, int pos) {
   		if (pos == spaces.size()) {//当所有需要填写数字的格子都填了数字
   			valid = true;
   			return;
   		}
   		auto [i, j] = spaces[pos];
   		for (int digit = 0; digit < 9&&!valid ; ++digit) {//如果已经有解了就剪枝
   			if (!line[i][digit] && !column[j][digit] && !block[i / 3][j / 3][digit]) {//行列和九宫格中都没有元素重复
   				line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true;
   				board[i][j] = digit + '0' + 1;
   				dfs(board, pos + 1);
   				line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = false;
   			}
   		}
   	}

   	void solveSudoku(vector<vector<char>>& board) {
   		for (int i = 0; i < 9; ++i) {
   			for (int j = 0; j < 9; ++j) {
   				if (board[i][j] == '.') {
   					spaces.push_back({i,j});
   				} else {
   					int digit = board[i][j] - '0' - 1;//因为真实数据和数组下标相差1
   					line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true;
   				}
   			}
   		}

   		dfs(board, 0);
   	}
};


posted @ 2021-03-04 13:23  coderJ_ONE  阅读(34)  评论(0编辑  收藏  举报