LeetCode 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.

image

A sudoku puzzle...

image

...and its solution numbers marked in red.

大意就是给你一个不完成的数独, 让你填完整。

直接dfs, 用三个数组记录行,列, 块就可以了

class Solution {
    bool dfs(vector<vector<char>>& board, bool row[10][10], bool val[10][10], bool rtl[10][10], int x, int y)
    {
        while(x < 9 && y < 9 && board[x][y] != '.')
        {
            y ++;
            if(y == 9)
                x ++, y = 0;
        }
        
        if(x >= 9)
            return true;
        
        for(int i=1; i<10; ++ i)
        {
            if(row[x][i] == false &&  val[y][i] == false &&  rtl[x/3*3+y/3][i] == false)
            {
                board[x][y] = '0' + i;
                row[x][i] = val[y][i] = rtl[x/3*3+y/3][i] = true;
                
                if(dfs(board, row, val, rtl, x + (y+1 == 9), (y+1==9) ? 0 : y + 1))
                    return true;
                
                row[x][i] = val[y][i] = rtl[x/3*3+y/3][i] = false;
            }
        }
        board[x][y] = '.';
        return false;
    }
public:
    void solveSudoku(vector<vector<char>>& board) {
        
        bool row[10][10], val[10][10], rtl[10][10];
        memset(row, false, sizeof(row));
        memset(val, false, sizeof(val));
        memset(rtl, false, sizeof(rtl));
        
        for(int i = 0; i < 9; ++ i)
        {
            for(int j = 0; j < 9; ++ j)
            {
                if(board[i][j] == '.')
                    continue;
                int t = board[i][j] - '0';
                if(row[i][t] || val[j][t] || rtl[i / 3 * 3 + j / 3][t])
                    continue;
                row[i][t] = val[j][t] = rtl[i / 3 * 3 + j / 3][t] = true;
            }
        }
        
        dfs(board, row, val, rtl, 0, 0);
    }
};
posted @ 2017-03-22 09:05  aiterator  阅读(109)  评论(0编辑  收藏  举报