Skip to content

Convert recursive DFS to iterative stack-based implementation - #29

Merged
shakayami merged 1 commit into
masterfrom
claude/maxflow-dfs-iterative-vsg7ld
Jul 11, 2026
Merged

Convert recursive DFS to iterative stack-based implementation#29
shakayami merged 1 commit into
masterfrom
claude/maxflow-dfs-iterative-vsg7ld

Conversation

@shakayami

Copy link
Copy Markdown
Owner

Summary

Refactored the DFS function in the max flow algorithm from a recursive implementation to an iterative stack-based approach. This change improves robustness by eliminating potential stack overflow issues on deep graphs while maintaining the same algorithmic correctness.

Key Changes

  • Converted recursive DFS to iterative implementation: Replaced the recursive dfs(v, up) function with an iterative version using an explicit stack data structure
  • Updated function signature: Changed dfs(v, up) to dfs(s_, t_, up) to accept both source and target nodes, enabling the iterative approach
  • Introduced path tracking: Added a path list to track (node, edge_index) pairs during traversal, allowing capacity updates to be applied after finding an augmenting path
  • Refactored edge iteration logic: Moved the edge iteration into a while loop within the main stack processing loop, with explicit Iter[v] increment management
  • Simplified capacity updates: Consolidated capacity updates into a single loop that processes the discovered path in reverse order

Implementation Details

  • The iterative approach maintains a stack of (node, flow_into_node) tuples representing the current traversal state
  • When the source node is reached, the algorithm updates all edge capacities along the discovered path in a single pass
  • The level array invalidation (level[v] = self.n) is preserved to maintain the algorithm's efficiency properties
  • The function returns 0 when no augmenting path is found, consistent with the original behavior

https://claude.ai/code/session_01JAwRWVg1ZbRWobeGyFuc6a

@shakayami shakayami linked an issue Jul 11, 2026 that may be closed by this pull request
@shakayami
shakayami merged commit a6e0baa into master Jul 11, 2026
19 checks passed
@shakayami
shakayami deleted the claude/maxflow-dfs-iterative-vsg7ld branch July 11, 2026 07:16
@shakayami shakayami linked an issue Jul 16, 2026 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

maxflow maxflowで再帰を使ってるから遅い

2 participants