2,635 questions
2
votes
2
answers
112
views
When to mark visited in iterative DFS? at push or at pop
I'm working on implementing the iterative (non-recursive) version of dfs. I'm confused when to mark a node as visited: at push or at pop.
In bfs, we mark visited when pushing it to queue, so it seems ...
Advice
0
votes
2
replies
37
views
DFS VS DSFVisit
I'm in college learning about DFS and BFS. I knew about this before, although what's throwing me in a loop is DFSVisit.
I just want to know what's the difference between DFS and DFSVisit. Is DFS just ...
0
votes
1
answer
36
views
Avoid counting waiting time before the first departure in DFS-based pathfinding graph
I have a graph-based travel system where each city has two stations: a bus station and a train station. Each station is represented as a node (Node), and each connection/departure is represented as an ...
0
votes
0
answers
50
views
How to determine left and right indices quickly in depth-first ordered implicit binary tree?
Suppose I have a complete, perfect binary tree stored in an array. If I store node data in breadth-first traversal order (Eytzinger order), then if an internal node's index is i, its left and right ...
7
votes
1
answer
105
views
How to extend a spanning tree into a bridgeless subgraph in O(V+E) time?
I'm working on the following problem:
Given an undirected graph G = (V, E), represented as an adjacency list, design an efficient algorithm to construct a subgraph H = (V, E') such that:
E' is a ...
3
votes
1
answer
156
views
How can I efficiently parallelize and optimize a large-scale graph traversal algorithm in Python to handle millions of nodes?
I'm working on Python project that involves processing a very large graph - it has millions of nodes and edges. The goal is to perform a breadth-first search (BFS) or depth-first search (DFS) from a ...
0
votes
1
answer
82
views
Does this DFS approach for detecting cycles in a directed graph work correctly, or are there hidden issues?
I'm trying to detect cycles in a directed graph using a DFS-based approach in Java. I implemented a solution that uses a visited[] array and builds map from the input edge list. It seems to work ...
1
vote
1
answer
135
views
Shortest path through a labyrinth: not always getting correct result
I am trying to solve the CSES challenge Labyrinth:
Labyrinth
You are given a map of a labyrinth, and your task is to find a path from start to end. You can walk left, right, up and down.
Input
The ...
6
votes
4
answers
419
views
Maximum number of cars on m x n parking lot (single empty region with all marked cells adjacent to it)
The problem
I am trying to solve a competitive programming problem which goes like that:
Given an m x n rectangular grid, what the maximum number of cars than can be parked (each car takes 1 cell) so ...
-2
votes
1
answer
142
views
Why time complexity for Longest Increasing Path in a Matrix is O(nm)?
I am having a hard time understanding the time complexity for the solution to the following LeetCode problem 329. Longest Increasing Path in a Matrix:
Given an m x n integers matrix, return the ...
0
votes
1
answer
52
views
Speedup depth first search in a grid
I am currently working on leetcode 994. Rotting Oranges. Where the description is given as follows:
You are given an m x n grid where each cell can have one of three values; 0 represents an empty ...
0
votes
1
answer
90
views
Why is my DFS maze generation algorithm not working?
I have a DFS maze generation algorithm implementation in c++ that seems to consistently create multiple distinct areas. The maze is represented as a 2d vector of Node objects, which create a connected ...
2
votes
2
answers
92
views
Predecessors from scipy depth_first_order
I use scipy version 1.14.1 to traverse the minimum spanning tree in depth-first order, but I do not understand some results, namely the predecessors returned by scipy are not correct.
Here is an ...
0
votes
2
answers
119
views
Efficient connected components from a 2D array
In an m x n matrix consisting of 0s and 1s, we are tasked with counting the 4-directionally connected islands of 1s. A python implementation is as follows:
def numIslands(grid):
def sink(i,...
0
votes
1
answer
71
views
DFS-compatible coordinate-free neighbors in Haskell
I've recently found myself solving a lot of 2D matrix search problems. A typical approach looks like the skeleton below, which searches for a word along 4-directionally connected paths in a 2D array:
...
2
votes
1
answer
104
views
How to implement Depth First Search on a Weighted Adjacency List Graph? [closed]
I'm working on a depth first search of a weighted graph from an adjacency list. I know that technically weighted shouldn't make a difference here, but it does in how my vectors are setup and I'm not ...
0
votes
1
answer
292
views
Why is this DFS + Memoization solution for selecting indices in two arrays too slow while a similar approach is more efficient?
I was solving LeetCode problem 3290. Maximum Multiplication Score:
You are given an integer array a of size 4 and another integer array b of size at least 4.
You need to choose 4 indices i0, i1, i2, ...
0
votes
1
answer
107
views
Depth First Search with a stack (specifically a la CLRS with parent and timestamp attributes)
Cormen, Leiserson, Rivest, and Stein (CLRS) give (section 22.3) a recursion-based implementation of DFS that not only adds parent data u.parent to each node u along the way but also timestamp fields u....
3
votes
1
answer
196
views
String representation of a tree (nodes) data structure with paths from left to right
Given a tree-like data structure of nodes with each node having a property children that contains the children nodes from left to right, I wish to create a string representation of this data structure ...
0
votes
1
answer
49
views
Why is there no sp-back edge indicated between two specific nodes in this DJ Graph?
I am reading the paper Identifying Loops Using DJ Graphs by Sreedhar et al. In this paper, they present the following classification of edges in a depth first search ordering of a graph (specifically ...
0
votes
1
answer
152
views
Shapely multilinestring: depth first search
I have a Shapely multiline string that has multiple branches that I want removed. I've attached an image where the red is the main line that I want to keep and the black are to be removed.
I can't ...
1
vote
2
answers
121
views
Can this generic DFS implementation in Haskell be used to detect cycles in an adjacency list?
Consider the following polymorphic DFS function from here:
-- | Depth-first search.
--
-- Generates the list of unique visited states from a
-- given starting state. States are unique up to the
-- ...
0
votes
0
answers
45
views
Logical Error in my implementation for the problem "Draughts" of Codechef
I have written this code for the problem "Draughts" of codechef but only few testcases are getting passed. Can anyone tell what is the error in my logic?
Furik and Rubik have come to the ...
-1
votes
2
answers
109
views
Yield depth on a depth-first non-recursive tree walker?
I'm trying to find a non-recursive "powerful/versatile" tree walker algorithm, ultimately yielding not just the node but the depth of the node, its parent and its sibling index, and able to ...
-1
votes
1
answer
107
views
Why doesn't my DFS work on this 8 puzzle?
I'm trying to run DFS on this 8 puzzle solver. the initial state is like this:
1 4 2
3 _ 5
6 7 8
where '_' represents a space.
the goal state is this (formatted in my code as _12345678):
_ 1 2
3 4 5
...
0
votes
2
answers
88
views
Difference between passing in string vs. array parameters to recursive function
This may be a dumb question so I am sorry, but there is a Leetcode problem where you have to return all of the paths from the root node to leaf nodes in an array of strings connected with "->&...
2
votes
1
answer
83
views
Depth First Search Time Complexity
Below is Python code for a depth search algorithm.
def add_edge(adj, s, t):
# Add edge from vertex s to t
adj[s].append(t)
# Due to undirected Graph
adj[t].append(s)
print('adj add ...
0
votes
0
answers
51
views
Skill Tree Closed Cycle Detection
In the following script, my current problem is with "CanDisableSkill()"
That's called for the purpose to check if the node is inside a closed cycle of turned on nodes. Which in that case you ...
1
vote
0
answers
183
views
What are the most efficient algorithms for detecting cycles in a directed graph?
I am working on a problem where I need to detect cycles in a directed graph. The graph is represented using an adjacency list, and it can have a large number of nodes and edges. I am looking for the ...
0
votes
1
answer
50
views
How to Ensure Correct Alternation Between Addition and Subtraction in DFS for Matrix Traversal?
I'm working on a DFS algorithm to traverse an 8x8 matrix where I need to alternate between addition and subtraction while updating the maximum values for each cell. But it is not working as I want it ...
0
votes
0
answers
51
views
Detect Cyclic Islands on a Matrix
On a binary matrix M, a cyclic island is a region of 1s where the region encircles itself (horizontal, vertical and cross directions are allowed)
Given a matrix M,
Allowing neighbors to be in any of ...
2
votes
1
answer
107
views
Is it possible to solve LeetCode 1653 using recursion?
I am trying to solve LeetCode problem 1653. Minimum Deletions to Make String Balanced:
You are given a string s consisting only of characters 'a' and 'b'.
You can delete any number of characters ...
1
vote
0
answers
63
views
Should DFS check validity before or after call - traversing 2D Array
Are either of these more efficient or standard/readable? This is assuming that visited is not always empty/all False. The second option seems to do less checks: I wrote how many checks take place for ...
1
vote
1
answer
55
views
Why can memoisation inside the DFS lead to wrong value?
The problem is from leetcode 2976. Minimum Cost to Convert String I
The problem is that we have to convert source to target. We can use original[i] and replace it with changed[i]. Any pair of original[...
1
vote
1
answer
83
views
Java DepthFirstSearch Algorithm not working
I have tried to code a depthfirstsearch algorithm to solve a maze. This is what I have so far. I have tried to add as much detail so the logic is understandable:
//Upgraded dfs algorithm that creates ...
3
votes
1
answer
145
views
How does Prolog "redo" search when backtracking
I think that I understand how Prolog uses unification and backtracking to find the first match. However I'm having a hard time trying to understand what does it do when it is asked to "redo" ...
0
votes
4
answers
246
views
Traverse over tree type structured data using JavaScript
I have a data set having parent and nested children in it. The purpose of this data is to traverse over parent.
1
/ \
2 3
/ \ / \
4 5 6 7
First traverse 1,2,4 Now 4 has no ...
-12
votes
1
answer
205
views
Knight's journey solution gives incorrect output? [closed]
The knights journey where we are given the start/end points and the size of board(n*n):
Find the minimum steps to reach the end from the starting point. If no path is there return -1:
I've tried ...
-1
votes
0
answers
80
views
Why use two arrays of insertion_time and lowest_insert_time in Tarjans algorithm for Bridges in Graph? [duplicate]
I've been working on the LeetCode problem 1192. Critical Connections in a Network. From various sources, I have the following code:
class Solution {
int timer = 1;
void dfs(int node, int ...
1
vote
1
answer
172
views
Single Source - Single Destination Shortest Path (DFS + DP) - Time complexity?
Context:
I want to write an algorithm for finding the shortest(least cost) path from a fixed source to a fixed destination node in a weighted directed graph with non negative weights (can have cycles)....
2
votes
1
answer
138
views
Topological Sort as Reverse Post-DFS | Course Schedule II LeetCode
Currently solving Course Schedule II on LeetCode and this is the code that DOES NOT pass all test cases because of the following line: Collections.reverse(postOrder);. Removing this line solves all ...
1
vote
1
answer
117
views
Why is BFS is much quicker than DFS when I implement both of them?
I am trying to use DFS and BFS to find all simple paths that have lengths up to a given k, starting at a given vertex in a directed graph. No cycles are allowed.
My code is as follows, and I have ...
1
vote
1
answer
165
views
Word Hunt DFS Algorithm Not Finding Optimal Solution
I am trying to code an algorithm for the Word Hunt game on Iphone Game Pigeon.
How word hunt works:
There is a 4x4 grid of letters given to each player. Each player must form words that are three ...
2
votes
0
answers
126
views
Are BFS and DFS the same and just the Monad is different?
I wrote a tail-recursive BFS in Scala:
import scala.collection.mutable
/** Do BFS from start and return the smallest distance to end (None if not connected) */
def bfs[A](start: A, end: A, neighbors: ...
0
votes
1
answer
178
views
Tarjan Algorithms for SCC
I am stumbled at this part of SCC. I know that 5,6,7 is a strongly connected component. Performing the tarjan Algorithm for SCC starting at no
de 5, I get unsatisfied values of low-link at 7.
Graph ...
1
vote
0
answers
93
views
Shortest path in Directed Acyclic Graph. Is topological Sort Really needed?
Here's a famous problem:
Given a Directed Acyclic Graph of N vertices from 0 to N-1 and a 2D Integer array(or vector) edges[ ][ ] of length M, where there is a directed edge from edge[i][0] to edge[i][...
1
vote
1
answer
41
views
How do i add memoization when calculating longest subsequence for an integer array?
I'm doing https://leetcode.com/problems/longest-increasing-subsequence/
I know in theory that each index needs to be assigned a length but i'm having trouble coding it up using my iterative approach
/*...
1
vote
0
answers
154
views
Dfs in assembly function
I tried to do this function DFS recursively in assembly and I keep recieving "Segmentation fault" and I don't know from where.
neighbours_t expand(uint32_t node);
void dfs(uint32_t node, ...
1
vote
1
answer
107
views
133. Clone Graph: Node with value 2 doesn't exist in the original graph
I get a similar error with a different root cause compared to: Clone Graph LeetCode 133
Consider the below implementation. If I use a Node-type key for processed_node_map, the algorithm passes. If I ...
1
vote
0
answers
49
views
Depth-First Search for Optimal Route Not Returning Expected Results in C#
I'm working on a program to find an optimal travel route starting and ending at the same city. The goal is to find the best route with the best goodness rating of the visited cities. My data is read ...