[leetcode]Sudoku Solver

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   ar   

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.

演算法思路:

典型的DFS,與N-Queens其實沒太大區別,只是衝突不同,而衝突的判斷方式,在[leetcode]Valid Sudoku中已經講得很清楚了。

代碼如下:

 1 public class Solution { 2     boolean over = false; 3     public void solveSudoku(char[][] board) { 4         if(board == null || board.length != 9 || board[0].length != 9) return; 5         boolean[][] row = new boolean[9][9]; 6         boolean[][] col = new boolean[9][9]; 7         boolean[][] matrix = new boolean[9][9]; 8         for(int i = 0; i < 9; i++){//初始化衝突表 9             for(int j = 0; j < 9; j++){10                 if(board[i][j] != ‘.‘){11                     int n = board[i][j] - ‘1‘;12                     row[i][n] = col[j][n] = matrix[i - i % 3 + j / 3][n] = true;13                 }14             }15         }16         dfs(board,0,0,row,col,matrix);17     }18     private void dfs(char[][] board,int i ,int j,boolean[][] row,boolean[][] col,boolean[][] matrix){19         if(i > 8){20             over = true;21             return;22         }23         if(board[i][j] != ‘.‘){24             if(j < 8){25                 dfs(board, i, j + 1, row, col, matrix);26             }else{27                 dfs(board, i + 1, 0, row, col, matrix);28             }29         }else{30             for(int k = 0; k < 9; k++){31                 if(row[i][k] || col[j][k] || matrix[i - i % 3 + j / 3][k]) continue;32                 row[i][k] = col[j][k] = matrix[i - i % 3 + j / 3][k] = true;33                 board[i][j] = (char)(‘1‘ + k);34                 if(j < 8){35                     dfs(board, i, j + 1, row, col, matrix);36                 }else{37                     dfs(board, i + 1, 0, row, col, matrix);38                 }39                 if(over) return;40                 row[i][k] = col[j][k] = matrix[i - i % 3 + j / 3][k] = false;41                 board[i][j] = ‘.‘;42             }43         }44     }45 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.