|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
湊个热闹,递归算法,92种解,结果放在数组中,未进行外显处理
- Dim Queen() As Integer '数组索引为 行号,值为 列号
- Dim arrResult As Variant
- Sub Main()
- ReDim Queen(1 To 8) As Integer
- FindPlace 1
- MsgBox "共有【" & UBound(arrResult, 2) & "】组解"
- End Sub
- Function FindPlace(intCurRowID As Integer)
- Dim intColID As Integer, intNextRowID As Integer
-
- For intColID = 1 To 8
- If CanPlaced(intCurRowID, intColID) Then
- Queen(intCurRowID) = intColID
- If intCurRowID = 8 Then
- GetResult
- Exit Function
- End If
- intNextRowID = intCurRowID + 1
- FindPlace intNextRowID
- End If
- Next
- Queen(intCurRowID) = 0
- End Function
- Function CanPlaced(intCurRowID As Integer, intCurColID As Integer) As Boolean
- Dim intRow As Integer
-
- For intRow = 1 To intCurRowID - 1
- '同一列有皇后
- If Queen(intRow) = intCurColID Then
- CanPlaced = False
- Exit Function
- End If
- '同一主对角线(行号+列号 相等)
- If intRow + Queen(intRow) = intCurRowID + intCurColID Then
- CanPlaced = False
- Exit Function
- End If
- '同一主对角线(行号-列号 相等)
- If intRow - Queen(intRow) = intCurRowID - intCurColID Then
- CanPlaced = False
- Exit Function
- End If
- Next
- CanPlaced = True
- End Function
- Sub GetResult()
- Dim lngCol As Long, lngRow As Integer
-
- If IsArray(arrResult) Then
- lngCol = UBound(arrResult, 2) + 1
- ReDim Preserve arrResult(1 To 8, 1 To lngCol) As Integer
- Else
- lngCol = 1
- ReDim arrResult(1 To 8, 1 To 1) As Integer
- End If
- For lngRow = LBound(Queen) To UBound(Queen)
- arrResult(lngRow, lngCol) = Queen(lngRow)
- Next
- End Sub
复制代码 |
|