赞
踩
题目
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...
意思就是给出一个数独题,还没填数字的用'.'来表示。
算法思路:
数独游戏我们应该都玩过,规则就是每行没列每个九格宫都不能出现有相同的数字。那么在做这个题的时候,我们可以记录每一行、每一列、每个九宫格已经出现的数字,然后这样能就这可以知道每个格子可以尝试填哪些数字,填了数字以后立刻更新每一行、每一列、每个九宫格出现的数字,然后使用回溯便可以把题目做出来。该算法最坏情况下就是全部都没有填,相当于每行都做一个全排列,坏时间复杂度是O(9!^9),算法实现如下:
- class Solution {
- public:
- bool fillSudoku(vector<vector<char>>& board, int i, int j){
- if(i==9) return true;
- if(board[i][j]=='.'){
- for(int k=1; k<=9; ++k){
- if(!row[i][k]&&!col[j][k]&&!grid[i/3][j/3][k]){
- board[i][j] = '0'+k;
- row[i][k] = 1, col[j][k] = 1, grid[i/3][j/3][k] = 1;
- bool success = fillSudoku(board,i+(j+1)/9,(j+1)%9);
- if(success) return true;
- board[i][j] = '.';
- row[i][k] = 0, col[j][k] = 0, grid[i/3][j/3][k] = 0;
- }
- }
- }
- else
- return fillSudoku(board,i+(j+1)/9,(j+1)%9);
-
- return false;
- }
-
- void solveSudoku(vector<vector<char>>& board) {
- memset(row,0,sizeof(row));
- memset(col,0,sizeof(col));
- memset(grid,0,sizeof(grid));
- int n1 = board.size();
- int n2 = board[0].size();
- for(int i=0; i<n1; ++i){
- for(int j=0; j<n2; ++j){
- if(board[i][j]!='.'){
- row[i][board[i][j]-'0'] = 1;
- col[j][board[i][j]-'0'] = 1;
- grid[i/3][j/3][board[i][j]-'0'] = 1;
- }
- }
- }
- fillSudoku(board,0,0);
- return ;
- }
- private:
- bool row[9][10],col[9][10],grid[3][3][10];
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。