回溯演算法 -- 數獨問題__演算法

來源:互聯網
上載者:User
還是上遇到的題,彷彿成了初戀一般又愛又恨。。。
數獨問題


你一定聽說過“數獨”遊戲。
如圖,玩家需要根據9×9盤面上的已知數字,推理出所有剩餘空格的數字,並滿足每一行、每一列、每一個同色九宮內的數字均含1-9,不重複。

數獨的答案都是唯一的,所以,多個解也稱為無解。

本圖的數字據說是芬蘭數學家花了3個月的時間設計出來的較難的題目。但對會使用電腦編程的你來說,恐怕易如反掌了。

本題的要求就是輸入數獨題目,程式輸出數獨的唯一解。我們保證所有已知資料的格式都是合法的,並且題目有唯一的解。

格式要求,輸入9行,每行9個字元,0代表未知,其它數字為已知。
輸出9行,每行9個數字表示數獨的解。



思路:依然是暴力+回溯,依次判斷每一行每一列從0-9可以放入的數,然後遞迴。

0-9抖不滿足條件時,回溯到上一個。

代碼:

package lanqiaobei;import java.io.*;import java.util.Scanner;public class shudu {public int a[][] = new int[9][9];public boolean is_row_col_repeat(int row,int col,int n){for(int i=0;i<9;i++){if(a[row][i] == n)return false;}for(int i=0;i<9;i++){if(a[i][col] == n)return false;}return true;}public int get_row_range(int row){//判斷同色的格子時,判斷為哪個大格子if(0<=row && row<=2)return 0;else if(3<=row && row<=5)return 3;else return 6;}public int get_col_range(int col){//判斷同色的格子時,判斷為哪個大格子if(0<=col && col<=2)return 0;else if(3<=col && col<=5)return 3;else return 6;}public boolean is_block_repeat(int x,int y,int n){for(int i=x;i<=x+2;i++)for(int j=y;j<=y+2;j++){{if(a[i][j] == n)return false;}}return true;}public void dfs(int row,int col){if(row >= 9){for(int i=0;i<=8;i++){for(int j=0;j<=8;j++){System.out.print(a[i][j]);}System.out.println("");}}int x = get_row_range(row);int y = get_col_range(col);if(a[row][col] == 0){for(int i=1;i<=9;i++){//數字1-9if( is_row_col_repeat(row,col,i) && is_block_repeat(x,y,i)){a[row][col] = i;dfs(row + (col + 1) / 9, (col + 1) % 9);}}//如果1-9都不行a[row][col] = 0;return;}else {dfs(row + (col + 1) / 9, (col + 1) % 9);}}public static void main(String[] args) {// TODO Auto-generated method stubshudu s = new shudu();Scanner scanner = new Scanner(System.in);String str;char[] ai;for(int i = 0; i < 9; i++) {str = scanner.nextLine();ai = str.toCharArray();for(int j = 0; j < 9; j++) {s.a[i][j] = Integer.parseInt(ai[j] + "");}}s.dfs(0, 0);}/*005300000800000020070010500400005300010070006003200080060500009004000030000009700 */}

輸入

005300000

800000020

070010500

400005300

010070006

003200080

060500009

004000030

000009700

輸出答案:

145327698

839654127

672918543

496185372

218473956

753296481

367542819

984761235

521839764

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.