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



solution:用dfs来做,统计所有的为空的格子,然后依次访问每个格子,对该格子填1-9,判断成立则访问递归调用访问下一个格子,否则置回.值,继续填下一个数。结束条件是访问到最后一个格子,即cur == len -1

此处用dots数组记录空格子的索引,将二维数组索引视为一维进行添加。


class Solution {
public:
    void solveSudoku(vector<vector<char> > &board) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
 
        vector<int>dots;
        for(int row = 0; row < 9; row++)
        {
            for(int col = 0; col < 9; col++)
            {
                if(board[row][col] == '.')
                {
                    int temp = row * 9 + col;
                    dots.push_back(temp);
                }
            }
        }
        int len = dots.size();
        sudokuSolver(dots, 0, len, board);
    }
    
    bool sudokuSolver(vector<int>dots, int cur, int len, vector<vector<char> > &board)
    {
        if(cur == len) return true;
        int num = dots[cur];
        int row = num / 9;
        int col = num % 9;
        
        for(int nu = 0; nu < 9; nu++)
        {
            if( isValid(nu, row, col, board) )
            {
                char res = (char)('1' + nu);
                board[row][col] = res;
                if( sudokuSolver(dots, cur+1, len, board) )
                    return true;
                board[row][col] = '.';
            }
        }
        
        return false;
    }
    
    
    bool isValid(int nu, int row, int col, vector<vector<char> > &board)
    {
        for( int i = 0; i < 9; i++ )
        {
            int rowVal = board[ row][ i ] - '1';
            int colVal = board[ i ][ col ] - '1';
            int blockVal = board[ row - row%3 + i/3 ][ col - col%3 + i%3 ] - '1';
            if(rowVal == nu || colVal == nu || blockVal == nu)
                return false;
        }
        return true;
    }
    
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值