Public Class Form1 Private Const N = 200, M = 200 Private Const N1 = N - 1, M1 = M - 1 Private A(N1, M1) As Byte : Private D(N, M) As Byte Private HX(N * M), HY(N * M) Dim img As New Bitmap(200, 200) '300x300サイズのImage Private Sub セル初期設定() For i = 0 To N1 For j = 0 To M1 A(i, j) = 0 : D(i, j) = 0 Next Next End Sub Private Sub セル設定() ' 乱数によるセル設定 Dim X As Integer, Y As Integer Do : X = Int(N * Rnd()) : Y = Int(M * Rnd()) Loop Until A(Y, X) = 0 A(Y, X) = 1 : img.SetPixel(X, Y, Color.Black) End Sub Private Function 浸透() As Long セル初期設定() : Randomize() For i = 1 To M1 セル設定() Next For i = M1 To 40000 If (i Mod 200) = 0 Then Label1.Text = i : Me.Refresh() End If セル設定() If 判定() Then 浸透 = i : Exit Function End If Next 浸透 = -1 End Function Private Function 方向判定(i As Integer, j As Integer, K As Integer) As Boolean If j > M1 Then 方向判定 = True For ii = 0 To K - 1 img.SetPixel(HX(ii), HY(ii), Color.Red) Next ElseIf j < 0 Or i < 0 Or i > M1 Then : 方向判定 = False ElseIf D(i, j) <> 0 Then : 方向判定 = False Else D(i, j) = 1 ' 以前来たことがあることを示すフラグ If A(i, j) = 0 Then 方向判定 = False Else HX(K) = j : HY(K) = i 方向判定 = 方向判定(i, j + 1, K + 1) ' j正方向試行 If 方向判定 Then Exit Function 方向判定 = 方向判定(i, j - 1, K + 1) ' j負方向試行 If 方向判定 Then Exit Function 方向判定 = 方向判定(i + 1, j, K + 1) ' i正方向試行 If 方向判定 Then Exit Function 方向判定 = 方向判定(i - 1, j, K + 1) ' i負方向試行 End If End If End Function Private Function 判定() As Boolean Dim S As Byte For i = 0 To N1 For j = 0 To M1 D(i, j) = 0 Next Next 判定 = True For i = 0 To N1 If A(i, 0) <> 0 Then S = 方向判定(i, 0, 0) : If S Then Exit Function End If Next 判定 = False End Function Private Function coff() As Double Dim CC As Integer For i = 0 To N1 For j = 0 To M1 If A(i, j) <> 0 Then CC = CC + 1 Next Next coff = 100.0 * CC / CDbl(N * M) End Function Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Dim j As Integer Dim g As Graphics = Graphics.FromImage(img) : g.Clear(Color.White) '描画クリア Cursor.Current = Cursors.WaitCursor '描画処理中、カーソルを待ち状態にする j = 浸透() : Label1.Text = "" PictureBox1.Image = img : g.Dispose() 'リソースを解放する If j < 0 Then MsgBox("試行に失敗しました") Else MsgBox("試行回数 = " & j & " 比率 " & Format(coff(), "##0.00") & " %") End If Cursor.Current = Cursors.Default ' End Sub End Class