I wrote an exhaustive recursive function to find the shortest path:
Private bestPath As String
Public Sub FindShortestPath()
Dim startCell As Range
Dim endCell As Range
Dim startPath As String
Dim nextMove As Long
Set startCell = Cells.Find("A")
Set endCell = Cells.Find("C")
bestPath = Space$(1024)
Application.ScreenUpdating = False
TryMoves startPath, startCell, endCell
Application.ScreenUpdating = True
For nextMove = 1 To Len(bestPath) - 1
Set startCell = MakeMove(startCell, CLng(Mid(bestPath, nextMove, 1)))
startCell.Formula = "=MID($Z$1," & Mid(bestPath, nextMove, 1) + 1 & ",1)"
Next nextMove
End Sub
Private Sub TryMoves(currentPath As String, currentCell As Range, targetCell As Range)
Dim thisMove As Long
Dim newCell As Range
If Len(currentPath) >= Len(bestPath) Then Exit Sub
For thisMove = 0 To 3
Set newCell = MakeMove(currentCell, thisMove)
If newCell.Address = targetCell.Address Then
' Found a path
If Len(currentPath) + 1 < Len(bestPath) Then bestPath = currentPath & CStr(thisMove)
ElseIf newCell.Value = "" Then
newCell.Value = "X"
TryMoves currentPath & CStr(thisMove), newCell, targetCell
newCell.Value = ""
End If
Next thisMove
End Sub
Private Function MakeMove(currentCell As Range, direction As Long) As Range
Select Case direction
Case 0
Set MakeMove = currentCell.Offset(-1, 0)
Case 1
Set MakeMove = currentCell.Offset(0, 1)
Case 2
Set MakeMove = currentCell.Offset(1, 0)
Case 3
Set MakeMove = currentCell.Offset(0, -1)
End Select
End Function
Public Sub ClearPath()
Cells.SpecialCells(xlCellTypeFormulas).ClearContents
End Sub
See attached. If you want to see it in action, comment out the line which turns off screen updating.
WBD
Bookmarks