1. 程式人生 > >輸入數獨題目,程式輸出數獨的唯一解。保證所有已知資料的格式都是合法的,並且題目有唯一的解。

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

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

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

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

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

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

例如:
輸入(即圖中題目):
005300000
800000020
070010500
400005300
010070006
003200080
060500009
004000030
000009700

程式應該輸出:
145327698
839654127
672918543
496185372
218473956
753296481
367542819
984761235
521839764

再例如,輸入:
800000000
003600000
070090200
050007000
000045700
000100030
001000068
008500010
090000400

程式應該輸出:
812753649
943682175
675491283
154237896
369845721
287169534
521974368
438526917
796318452


資源約定:
峰值記憶體消耗(含虛擬機器) < 256M
CPU消耗  < 2000ms


請嚴格按要求輸出,不要畫蛇添足地列印類似:“請您輸入...” 的多餘內容。

所有程式碼放在同一個原始檔中,除錯通過後,拷貝提交該原始碼。
注意:不要使用package語句。不要使用jdk1.7及以上版本的特性。
注意:主類的名字必須是:Main,否則按無效程式碼處理。


import java.util.Scanner;

public class Main {
	static int[][] d = new int[10][10];// 儲存輸入數獨的陣列1-9行,1-9列
	long start;
	long end;
	int count = 0;

	// 判斷行列是否重複
	boolean noLcAgain(int l, int c, int num) {
		int i;
		// 判斷行是否重複
		for (i = 1; i <= 9; i++) {
			if (d[l][i] == num)// 重複返回false
				return false;
		}
		// 判斷列是否重複
		for (i = 1; i <= 9; i++) {
			if (d[i][c] == num)// 重複返回false
				return false;
		}
		return true;
	}// 不重複時,返回true

	boolean noColorAgain(int l, int c, int num) {
		int i, j;
		int i1, j1;
		if (l >= 1 && l <= 3) {
			i1 = 1;
		} else if (l >= 4 && l <= 6) {
			i1 = 4;
		} else {
			i1 = 7;
		}

		if (c >= 1 && c <= 3) {
			j1 = 1;
		} else if (c >= 4 && c <= 6) {
			j1 = 4;
		} else {
			j1 = 7;
		}

		for (i = i1; i <= i1 + 2; i++)
			for (j = j1; j <= j1 + 2; j++)
				if (d[i][j] == num)
					return false;// 重複返回false

		return true;// 不重複時,返回true
	}

	void print() {
		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= 9; j++)
				System.out.print(d[i][j] + "");
			System.out.println("\n");
		}
	}

	// 深度優先搜尋
	void dfs(int l, int c) {
		if (l >= 10) {// 填完數時,打印出來
			end = System.nanoTime();
			System.out.println("執行時間:" + (end - start) / Math.pow(10, 9) + "s");
			print();
			System.exit(0);
		}

		int i;
		if (d[l][c] == 0) {// 該位置未填數字
			for (i = 1; i <= 9; i++) {
				if (noLcAgain(l, c, i) && noColorAgain(l, c, i)) {// 要填的i與其它數字不重複
					d[l][c] = i;
					if (count < 30) {
						System.out.println("l:" + l + " c:" + c + " i:" + i);// 列印填寫過程
						count++;
					}
					dfs(l + (c + 1) / 10, (c + 1) % 10);
				}
			}
			d[l][c] = 0;// 重新置0
		} else {
			dfs(l + (c + 1) / 10, (c + 1) % 10);
		}
	}

	public static void main(String[] args) {
		Main test = new Main();
		Scanner scanner = new Scanner(System.in);
		for (int i = 1; i <= 9; i++) {
			String s = scanner.nextLine();
			for (int j = 0; j < 9; j++) {
				String s1 = s.charAt(j) + "";
				d[i][j + 1] = Integer.parseInt(s1);
			}
		}
		test.start = System.nanoTime();
		test.dfs(1, 1);
		scanner.close();
	}
}