OK, this one has me baffled. I'm trying to teach myself more about recursive functions, so I'm making a prgoram to figure out the Knights Tour (http://en.wikipedia.org/wiki/Knight's_tour). It went well until I tried to run it. It stops randomly between 2,000 and 3,000 iterations with a Stack Overflow Error, yet its not doing a math operation. I thought it was a result of me using unsafe threading, so i removed threading, and it still threw the error. I removed the counter. Still error. Maybe someone can help me find this bug? Its a very sinple program....

The program uses an array of 0s and 1s to record where its "been". It uses another array of all the possible moves it can make, and tries those one at a time, brute force.

It also bugs me because I could understand if it was running out of memory, but it's not throwing a Out Of Memory error....

Public Class Form1
    Dim Chessboard(7, 7)
    Dim Moves(8) As Point
    Dim G As Double = 0
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
        For I = 0 To 7
            For J = 0 To 7
                Chessboard(I, J) = 0
            Next
        Next
        Moves(0) = New Point(3, 1)
        Moves(1) = New Point(1, 3)
        Moves(2) = New Point(3, -1)
        Moves(4) = New Point(-3, -1)
        Moves(5) = New Point(-3, 1)
        Moves(6) = New Point(-1, 3)
        Moves(7) = New Point(-1, -3)
        Moves(8) = New Point(1, -3)
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        CheckForIllegalCrossThreadCalls = False
        Dim T As New Threading.Thread(AddressOf startcheck)
        T.Start()
    End Sub

    Private Sub startcheck()
        Checkmove(New Point(0, 0))
    End Sub
    Private Sub Checkmove(ByVal location As Point)
        If Chessboard(location.X, location.Y) = 1 Then
            Exit Sub
        End If
        G += 1
        Label1.Text = G
        If TestBoard() Then MsgBox("Found it!")
        For Each M As Point In Moves
            If Not (location.X + M.X < 0 Or location.X + M.X > 7) Then
                If Not (location.Y + M.Y < 0 Or location.Y + M.Y > 7) Then
                    Checkmove(New Point(location.X + M.X, location.Y + M.Y))
                End If
            End If
        Next
        Chessboard(location.X, location.Y) = 0
    End Sub

    Private Function TestBoard()
        For I = 0 To 7
            For J = 0 To 7
                If Chessboard(I, J) = 0 Then Return False
            Next
        Next
        Return True
    End Function
End Class

Well, I found it. I, being the idiot I am, forgot to add this line

Chessboard(location.X, location.Y) = 1

so it wasn't recording progress.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.