1. 程式人生 > >LeetCode37. Sudoku Solver

LeetCode37. Sudoku Solver

題意:解9*9數獨

做法:回溯
對每一個還沒填充的格子,嘗試1~9這9個數字,如果是合法的,則繼續填充下一個格子,否則回溯。
判斷合法:只需要判斷對應行、對應列、對應3*3,有沒有矛盾。

設未被填充的格子個數為n,那麼時間複雜度大約為O(9n+1)=O(9n)
在leetcode上用時76ms,本題在leetcode上有0ms的解法,
2ms解法
0ms解法

class Solution {
public:
    void solveSudoku(vector<vector<char>>& board) {
        solve(board);
    }

private
: bool solve(vector<vector<char>>& board){ for(int i = 0; i < board.size(); ++i) for(int j = 0; j < board[0].size(); ++j){ if(board[i][j] == '.'){ for(int ch = '1'; ch <= '9'; ++ch) if(isValid(board, i, j, ch)){ board[i][j] = ch; if
(solve(board)) return true; else board[i][j] = '.'; } return false; } } return true; } bool isValid(vector<vector<char>>& board, int row, int col, char ch) { for
(int i = 0; i < board.size(); ++i){ int x = row / 3 * 3 + i / 3, y = col / 3 * 3 + i % 3; if(board[i][col] == ch || board[row][i] == ch || board[x][y] == ch) return false; } return true; } };