LeetCode37. Sudoku Solver

  1. Topic Link

    Portal

  2. The meaning of problems

    Sudoku games we have played, this question is given a 9 x 9 Sudoku board, you need to give a final legal chessboard

  3. Problem-solving ideas

    Like, see the code search mode at each position searches dfs feasible solution, not burst dfs layer stack 81, at ease dfs

  4. AC Code

     class Solution {
    
         public void solveSudoku(char[][] board) {
             solve(board, 0);
         }
    
         public boolean solve(char[][] board, int num) {
             if(num == 81) return true;
    
             int row = num / 9, col = num % 9;
             if(board[row][col] == '.') {
                 for(char ch = '1'; ch <= '9'; ++ch) {
                     if(isVaild(board, row, col, ch)) {
                         board[row][col] = ch;
                         if(solve(board, num + 1))
                             return true;
                         else
                             board[row][col] = '.';
                     }
                 }
                 return false;
             }
             return (solve(board, num + 1));
         }
    
         public boolean isVaild(char[][] board, int r, int c, char ch) {
             for(int i = 0; i < 9; i++) {
                 if(board[i][c] == ch) return false;
                 if(board[r][i] == ch) return false;
                 if(board[3 * (r / 3) + i / 3][3 * (c / 3) + i % 3] == ch) return false;
             }
             return true;
         }
     }
  5. PS

    The first time you use the markdown blog, rusty and stiff, 555 ~

Guess you like

Origin www.cnblogs.com/fan-jiaming/p/12121388.html