【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 the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character ‘.’.
在这里插入图片描述
A sudoku puzzle…
在这里插入图片描述
…and its solution numbers marked in red.

Note:

The given board contain only digits 1-9 and the character ‘.’.
You may assume that the given Sudoku puzzle will have a single unique solution.
The given board size is always 9x9.

思路

三个标记数组,行、列,3x3的单元,不能有重复的数字。
对每个空着的位置,尝试九个数字。深搜,回溯。

代码

class Solution {
public:
    void solveSudoku(vector<vector<char>>& board) {
        int n = 9, m = 9;
        vector<vector<int> > rows(n, vector<int>(10, 0));
        vector<vector<int> > cols(m, vector<int>(10, 0));
        vector<vector<int> > grid(9, vector<int>(10, 0));
        vector<pair<int, int> > st;
        
        for (int i=0; i<n; ++i) {
            for (int j=0; j<m; ++j) {
                if (board[i][j] != '.') {
                    int tmp = board[i][j] - '0';
                    rows[i][tmp] = 1;
                    cols[j][tmp] = 1;
                    grid[(i/3)*3 + j/3][tmp] = 1;
                }else {
                    st.push_back({i, j});
                }
            }
        }
        vector<vector<char>> copy = board;
        search(board, rows, cols, grid, st, 0, copy);
        board = copy;
        return;
    }
    
    void search (vector<vector<char>>& board, vector<vector<int>>& rows, vector<vector<int>>& cols, vector<vector<int>>& grid, vector<pair<int, int>>& st, int cnt, vector<vector<char>>& copy) {
        if (cnt == st.size()) {
            copy = board;
            return;
        }
        
        int x = st[cnt].first;
        int y = st[cnt].second;
        for (int j=1; j<=9; ++j) {
            if (rows[x][j]) continue;
            if (cols[y][j]) continue;
            if (grid[(x/3)*3+y/3][j]) continue;
            board[x][y] = j + '0';
            rows[x][j] = 1;
            cols[y][j] = 1;
            grid[(x/3)*3+y/3][j] = 1;
            search(board, rows, cols, grid, st, cnt+1, copy);
            board[x][y] = '.';
            rows[x][j] = 0;
            cols[y][j] = 0;
            grid[(x/3)*3+y/3][j] = 0;
        }
        return;
    }
};

这两天都脑壳痛。。。

发布了323 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/104840936