第12講 数独の問題を解くプログラムVer2解説 
第1話 Ver1からの変更点
数独の問題を解くプログラムVer2

Private Sub CommandButton1_Click()
  Dim i As Integer
  Dim j As Integer
  Worksheets("Sheet1").Cells(3, 1).Select
  syokika1
  dainyuu1
  mondaikaiseki
  bangousakusei (0)
  sakusei (0)

  If cn = 0 Then Cells(23, 1) = "解は存在しませんでした。"
  owari:
End Sub

Sub syokika1()

  cn = 0
  For i = 0 To 8
    For j = 0 To 8
      mah(i, j) = 0
      cnn(i, j) = 0
    Next
  Next

End Sub

Sub syokika2(g As Integer)

  For i = 0 To 8
    For j = 0 To 8
      hh = 1
      For k = 0 To g
        x = jz(k)
        y = iz(k)
        If i = y And j = x Then
          hh = 0
          Exit For
        End If
      Next
      If hh = 1 Then
        cnn(i, j) = 0
        For k = 0 To 100
          dhs(i, j, k) = 0
          dhs1(i, j, k) = 0
        Next
      End If
    Next
  Next


End Sub



Sub bangousakusei(h As Integer)

  
Dim i1, i2, i3, m As Integer
  
If cn = 1 Then Exit Sub
  
g = h
  
For i = 0 To 9
    For j = 0 To 8
      For k = 0 To 8
        If mah(j, k) = 0 Then
          If cnn(j, k) = i Then
            iz(g) = j
            jz(g) = k
            g = g + 1
          End If
        End If
      Next
    Next
  Next

  If h = 0 Then hs = g

End Sub

Sub sakusei(g As Integer)

  Dim i, j, k, l, hh, wa As Integer
  If cn = 1 Then Exit Sub
  j = jz(g)
  i = iz(g)

  mx = cnn(i, j)
  For k = 1 To mx
    mah(i, j) = dhs1(i, j, kk)
    If g + 1 < hs Then
      
syokika2 (g)
      
mondaikaiseki
      bangousakusei (g + 1)

      sakusei (g + 1)
      If cn = 1 Then Exit Sub
    Else
      cn = 1
      hyouji
      Exit Sub
    End If

  Next

  mah(i, j) = 0


End Sub

ピンクは新たに加えられた部分で、は変更された部分です。

第2話へ


VB入門講義応用編トップへ

VB入門講義トップへ