N Queen Problem
The N Queen, also known as eight queens puzzle, is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.
Public Const N As Integer = 4
Private Shared Sub PrintSolution(board As Integer(,))
For i As Integer = 0 To N - 1
For j As Integer = 0 To N - 1
Console.Write(" {0} ", board(i, j))
Next
Console.WriteLine()
Next
End Sub
Private Shared Function IsSafe(board As Integer(,), row As Integer, col As Integer) As Boolean
Dim i As Integer, j As Integer
For i = 0 To col - 1
If Convert.ToBoolean(board(row, i)) Then
Return False
End If
Next
i = row
j = col
While i >= 0 AndAlso j >= 0
If Convert.ToBoolean(board(i, j)) Then
Return False
End If
i -= 1
j -= 1
End While
i = row
j = col
While j >= 0 AndAlso i < N
If Convert.ToBoolean(board(i, j)) Then
Return False
End If
i += 1
j -= 1
End While
Return True
End Function
Private Shared Function SolveNQ(board As Integer(,), col As Integer) As Boolean
If col >= N Then
Return True
End If
For i As Integer = 0 To N - 1
If IsSafe(board, i, col) Then
board(i, col) = 1
If SolveNQ(board, col + 1) Then
Return True
End If
board(i, col) = 0
End If
Next
Return False
End Function
Public Shared Function Solve() As Boolean
Dim board As Integer(,) = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}
If SolveNQ(board, 0) = False Then
Return False
End If
PrintSolution(board)
Return True
End Function
Example
Dim isSolved As Boolean = Solve()
Output
isSolved: true
Output of Solve function:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0