Problem 3 (數獨 23%)
「數獨sudoku」來自日文,但概念源自「拉丁方塊」,是十八世紀瑞士數學家歐拉發明的。其遊戲規則為: 在九個九宮格裡,填入1到9的數字,讓每個數字在每個行、列及九宮格裡都只出現一次。謎題中會預先填入若干數字,其他宮位則留白,玩家得依謎題中的數字分佈狀況,邏輯推敲出剩下的空格裡是什麼數字,範例如下圖所示。請設計一個程式,可以幫助玩家提示空格中尚可填入的數字。例如:第5行第3列的位置尚可填入1這個數字;第6行第7列的位置尚可填入7與8這兩個數字;而第5行第5列的位置已有數字填入則輸出0。
輸入說明:輸入的第一列到第九列為數獨資料,每一列由九個數字所組成。數字1到9為已填入的數值,0代表尚未填入數值的空格,每個數字與數字間的區隔為一個空白符號。第十列及以後的資料為要提示位置的座標(座標的定義方式為右上角為9 1,左下角為1 9,第一個數字代表行,第二個數字代表列),當為0 0時表示結束。(請參照輸入範例)
輸入範例:test3.txt
4 0 0 8 0 5 0 1 0
2 0 0 0 0 9 0 8 0
6 0 8 0 0 3 4 9 0
0 0 5 0 2 0 6 0 0
0 0 1 0 7 0 9 0 0
0 0 7 0 8 0 3 0 0
0 9 0 1 0 0 0 0 2
0 8 0 4 0 0 0 0 9
0 3 0 6 0 2 0 0 7
5 3
6 7
5 5
0 0
輸出說明:每個提示位置有一列輸出結果,表示尚可填入的數字,請由小到大排列。每個數字與數字間的區隔為一個空白符號。若該位置已有填入數字,或找不到提示的數字則輸出0。(請參照輸出範例)
輸出範例:result3.txt
1
7 8
0
Dim x(9, 9), Lines
回覆刪除Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
For i = 1 To 9
For j = 1 To 9
Input #1, x(j, i)
Next
Next
Do While Not EOF(1)
Input #1, A, b
If A <> 0 And b <> 0 Then
If x(A, b) <> 0 Then Print #2, "0": GoTo A:
ans = ""
Lines = ""
For i = 1 To 9
Lines = Lines & " " & x(A, i)
Lines = Lines & " " & x(i, b)
Next
Call A1(A, b)
Print x(6, 1)
Print Lines
For i = 1 To 9
If InStr(Lines, i) = 0 Then ans = ans & " " & i
Next
If ans <> "" Then Print #2, ans Else Print #2, "0"
A:
End If
Loop
Close
Close
End
End Sub
Sub A1(ByVal A, ByVal b)
Do While A Mod 3 <> 0: A = A + 1: Loop
Do While b Mod 3 <> 0: b = b + 1: Loop
For i = A - 2 To A
For j = b - 2 To b
Lines = Lines & " " & x(i, j)
Next
Next
End Sub
Dim X(9, 9) As Byte
回覆刪除Dim Y(9) As Byte
Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
For i = 1 To 9
For j = 1 To 9
Input #1, X(j, i)
Next j
Next i
Do
Input #1, A, B
ans = ""
Dim OK(9) As Boolean
If A = 0 Then Exit Do
If X(A, B) <> 0 Then Print #2, 0: Exit Do
For i = 1 To 9
OK(i) = True
Next i
For i = 1 To 9
Y(i) = X(A, i)
Next i
For i = 1 To 9
If check(i) = False Then OK(i) = False
Next i
For i = 1 To 9
Y(i) = X(i, B)
Next i
For i = 1 To 9
If check(i) = False Then OK(i) = False
Next i
Select Case A
Case 1 To 3: AI = 1: AJ = 3
Case 4 To 6: AI = 4: AJ = 6
Case 7 To 9: AI = 7: AJ = 9
End Select
Select Case B
Case 1 To 3: BI = 1: BJ = 3
Case 4 To 6: BI = 4: BJ = 6
Case 7 To 9: BI = 7: BJ = 9
End Select
N = 1
For i = AI To AJ
For j = BI To BJ
Y(N) = X(i, j)
N = N + 1
Next j
Next i
For i = 1 To 9
If check(i) = False Then OK(i) = False
Next i
For i = 1 To 9
If OK(i) = True Then ans = ans & " " & i
Next i
If ans <> "" Then Print #2, ans Else Print #2, 0
Loop Until A = 0
Close #2
Close #1
End
End Sub
Function check(C) As Boolean
P = True
For i = 1 To 9
If Y(i) = C Then P = False: Exit For
Next i
check = P
End Function
in.txt-----------------
2 5 8 4 0 7 1 3 0
0 4 0 1 8 9 2 5 0
9 0 0 2 3 5 6 8 4
6 1 3 5 4 0 9 0 0
5 2 0 3 7 0 4 1 8
4 8 7 0 0 2 5 0 0
1 0 2 8 5 4 0 9 6
0 9 5 6 2 0 0 0 1
8 0 4 7 9 1 3 2 0
3 3
8 4
5 6
9 9
2 9
0 0
out.txt--------------------------
1
7
1 6
5
6