Skip to content

Commit

Permalink
Speed up path finding dfs by avoiding edges leading to visited nodes (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
tamirms authored Sep 17, 2021
1 parent 1acc65c commit 2be7469
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
33 changes: 19 additions & 14 deletions exp/orderbook/dfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,21 @@ type searchState interface {
) (xdr.Asset, xdr.Int64, error)
}

func contains(list []string, want string) bool {
for i := 0; i < len(list); i++ {
if list[i] == want {
return true
}
}
return false
}

func dfs(
ctx context.Context,
state searchState,
maxPathLength int,
visited []xdr.Asset,
visitedAssets []xdr.Asset,
visitedAssetStrings []string,
remainingTerminalNodes int,
currentAssetString string,
currentAsset xdr.Asset,
Expand All @@ -73,31 +83,25 @@ func dfs(
if err := ctx.Err(); err != nil {
return err
}
if currentAssetAmount <= 0 {
return nil
}
for _, asset := range visited {
if asset.Equals(currentAsset) {
return nil
}
}

updatedVisitedList := append(visited, currentAsset)
updatedVisitedAssets := append(visitedAssets, currentAsset)
updatedVisitedStrings := append(visitedAssetStrings, currentAssetString)

if state.isTerminalNode(currentAssetString, currentAssetAmount) {
state.appendToPaths(
updatedVisitedList,
updatedVisitedAssets,
currentAssetString,
currentAssetAmount,
)
remainingTerminalNodes--
}
// abort search if we've visited all destination nodes or if we've exceeded maxPathLength
if remainingTerminalNodes == 0 || len(updatedVisitedList) > maxPathLength {
if remainingTerminalNodes == 0 || len(updatedVisitedStrings) > maxPathLength {
return nil
}

for nextAssetString, offers := range state.edges(currentAssetString) {
if len(offers) == 0 {
if len(offers) == 0 || contains(visitedAssetStrings, nextAssetString) {
continue
}

Expand All @@ -113,7 +117,8 @@ func dfs(
ctx,
state,
maxPathLength,
updatedVisitedList,
updatedVisitedAssets,
updatedVisitedStrings,
remainingTerminalNodes,
nextAssetString,
nextAsset,
Expand Down
2 changes: 2 additions & 0 deletions exp/orderbook/graph.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ func (graph *OrderBookGraph) FindPaths(
searchState,
maxPathLength,
[]xdr.Asset{},
[]string{},
len(sourceAssets),
destinationAssetString,
destinationAsset,
Expand Down Expand Up @@ -380,6 +381,7 @@ func (graph *OrderBookGraph) FindFixedPaths(
searchState,
maxPathLength,
[]xdr.Asset{},
[]string{},
len(destinationAssets),
sourceAsset.String(),
sourceAsset,
Expand Down

0 comments on commit 2be7469

Please sign in to comment.