add: dfs test, and code fixes

This commit is contained in:
2026-03-12 23:08:53 -07:00
parent dc9bb41cce
commit 8e36afbf67
5 changed files with 341 additions and 72 deletions

68
samples/dfs.rpg Normal file
View File

@@ -0,0 +1,68 @@
**Free
Ctl-Opt DftActGrp(*No) Main(MainLine);
// --------------------------------------------------
// Global Graph Data (15 Nodes)
// --------------------------------------------------
Dcl-S AdjMatrix Ind Dim(15: 15) Inz(*Off);
Dcl-S Visited Ind Dim(15) Inz(*Off);
Dcl-S Found Ind Inz(*Off);
Dcl-Proc MainLine;
// 1. Setup a simple graph (Node 1 connected to 2 & 3, etc.)
AdjMatrix(1: 2) = *On; AdjMatrix(2: 4) = *On; AdjMatrix(4: 8) = *On;
AdjMatrix(1: 3) = *On; AdjMatrix(3: 5) = *On; AdjMatrix(5: 9) = *On; // Path to 9
AdjMatrix(3: 6) = *On; AdjMatrix(6: 10) = *On;
Dsply 'Starting DFS to find Node 9...';
// 2. Start Search from Node 1
DFS(1: 9);
If Not Found;
Dsply 'Node 9 was not found.';
EndIf;
Return;
End-Proc;
// --------------------------------------------------
// Recursive DFS Subprocedure
// --------------------------------------------------
Dcl-Proc DFS;
Dcl-Pi *N;
CurrentNode Int(10) Value;
TargetNode Int(10) Value;
End-Pi;
Dcl-S Neighbor Int(10);
// If already found elsewhere, stop exploring
If Found;
Return;
EndIf;
// Mark and Print current step
Visited(CurrentNode) = *On;
Dsply ('Visiting: ' + %Char(CurrentNode));
// Check if this is our target
If CurrentNode = TargetNode;
Dsply '*** MATCH FOUND! ***';
Found = *On;
Return;
EndIf;
// Explore Neighbors (1 to 15)
For Neighbor = 1 to 15;
If AdjMatrix(CurrentNode: Neighbor) And Not Visited(Neighbor);
DFS(Neighbor: TargetNode);
// If the recursive call found it, stop looping here too
If Found;
Return;
EndIf;
EndIf;
EndFor;
End-Proc;