leetcode记录37.Sudoku Solver

37.Sudoku Solver

√ Accepted
  √ 6/6 cases passed (20 ms)
  √ Your runtime beats 48.74 % of cpp submissions
  √ Your memory usage beats 10.11 % of cpp submissions (15.6 MB)
/*
 * @lc app=leetcode id=37 lang=cpp
 *
 * [37] Sudoku Solver
 */
class Solution {
public:
    void solveSudoku(vector<vector<char>>& board) {
        int flag = 0;
        sudoku(board, 0, flag);
    }

    void sudoku(vector<vector<char>>& board, int idx, int& flag)
    {
        if(idx == 81) {
            flag = 1;
            return;
        }

        int col = idx % 9;
        int row = idx / 9;

        if (board[row][col] != '.')
        {
            sudoku(board, idx + 1, flag);
        }else
        {
            vector<int> val(9);
            for (int i = 0; i < 9 ; i++)
            {
                if (board[i][col] != '.')
                {
                    val[board[i][col] - '1'] = 1;
                }
            }

            for (int i = 0; i < 9 ; i++)
            {
                if (board[row][i] != '.')
                {
                    val[board[row][i] - '1'] = 1;
                }
            }

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    int c = col - col % 3 + i;
                    int r = row - row % 3 + j;
                    if (board[r][c] != '.')
                    {
                        val[board[r][c] - '1'] = 1;
                    }
                }
            }

            for (int i = 0; i < 9 ; i++)
            {
                if (val[i] == 0)
                {
                    board[row][col] = i + '1';
                    sudoku(board, idx + 1, flag);
                    if (flag == 1)
                    {
                        return;
                    }
                }
            }
            board[row][col] = '.';

        }
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值