|
Sub 最短路径10()
Dim tm As Double, n As Long, k As Long
Dim stack As Collection ' 用于迭代模拟栈的集合
Dim visited() As Boolean '标记格子是否已访问
Dim tx(), ty(), ar, tar
Dim row As Long, col As Long, steps As Long
Dim i As Long, x As Long, y As Long
tm = Timer
n = [ag1]
tar = Range("a1").Resize(n + 2, 31).value
ar = tar
tx = Array(0, 1, 0, -1)
ty = Array(1, 0, -1, 0)
k = 1
ar(2, 2) = k
' 初始化栈,并将起始位置压入栈中
Set stack = New Collection
stack.Add Array(2, 2, k)
ReDim visited(1 To n + 2, 31)
Do While stack.count > 0
' 弹出栈顶元素
arr = stack(1)
stack.Remove 1
row = arr(0): col = arr(1): steps = arr(2)
ar(row, col) = steps
' 遍历四个方向
For i = 0 To 3
x = row + tx(i): y = col + ty(i)
' 检查是否到达终点
If ar(x, y) = "B" Then Exit Do
' 将新位置压入栈中
If ar(x, y) = -1 And Not visited(x, y) Then
stack.Add Array(x, y, steps + 1)
visited(x, y) = True
End If
Next i
Loop
' 输出路径
Dim r As Long, c As Long, p As Long, xP As Long, yP As Long
r = n + 1: c = 2
tar(r, c) = 0
Do
For p = 0 To 3
xP = r + tx(p)
yP = c + ty(p)
If ar(xP, yP) = ar(r, c) - 1 Then
r = xP: c = yP
tar(xP, yP) = 0
Exit For
End If
Next p
Loop Until r = 2 And c = 2 ' 起点是(2,2)
Range("a1").Resize(UBound(tar), UBound(tar, 2)) = tar
MsgBox "最少步数:" & steps & "步,耗时" & Format(Timer - tm, "0.00s")
End Sub
|
|