Skip to content

Commit e7b11aa

Browse files
add md articles (#5126)
* add kill-process.md article * add all-paths-from-source-lead-to-destination.md article * add web-crawler.md article * add number-of-islands-ii.md article
1 parent c2cf3a5 commit e7b11aa

File tree

4 files changed

+1162
-0
lines changed

4 files changed

+1162
-0
lines changed
Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
## 1. Depth First Search
2+
3+
::tabs-start
4+
5+
```python
6+
class Solution:
7+
8+
# We don't use the state WHITE as such anywhere. Instead, the "null" value in the states array below is a substitute for WHITE.
9+
GRAY = 1
10+
BLACK = 2
11+
12+
def leadsToDestination(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
13+
graph = self.buildDigraph(n, edges)
14+
return self.leadsToDest(graph, source, destination, [None] * n)
15+
16+
def leadsToDest(self, graph, node, dest, states):
17+
18+
# If the state is GRAY, this is a backward edge and hence, it creates a Loop.
19+
if states[node] != None:
20+
return states[node] == Solution.BLACK
21+
22+
# If this is a leaf node, it should be equal to the destination.
23+
if len(graph[node]) == 0:
24+
return node == dest
25+
26+
# Now, we are processing this node. So we mark it as GRAY.
27+
states[node] = Solution.GRAY
28+
29+
for next_node in graph[node]:
30+
31+
# If we get a `false` from any recursive call on the neighbors, we short circuit and return from there.
32+
if not self.leadsToDest(graph, next_node, dest, states):
33+
return False
34+
35+
# Recursive processing done for the node. We mark it BLACK.
36+
states[node] = Solution.BLACK
37+
return True
38+
39+
def buildDigraph(self, n, edges):
40+
graph = [[] for _ in range(n)]
41+
42+
for edge in edges:
43+
graph[edge[0]].append(edge[1])
44+
45+
return graph
46+
```
47+
48+
```java
49+
class Solution {
50+
51+
// We don't use the state WHITE as such anywhere. Instead, the "null" value in the states array below is a substitute for WHITE.
52+
enum Color { GRAY, BLACK };
53+
54+
public boolean leadsToDestination(int n, int[][] edges, int source, int destination) {
55+
56+
List<Integer>[] graph = buildDigraph(n, edges);
57+
return leadsToDest(graph, source, destination, new Color[n]);
58+
}
59+
60+
private boolean leadsToDest(List<Integer>[] graph, int node, int dest, Color[] states) {
61+
62+
// If the state is GRAY, this is a backward edge and hence, it creates a loop.
63+
if (states[node] != null) {
64+
return states[node] == Color.BLACK;
65+
}
66+
67+
// If this is a leaf node, it should be equal to the destination.
68+
if (graph[node].isEmpty()) {
69+
return node == dest;
70+
}
71+
72+
// Now, we are processing this node. So we mark it as GRAY
73+
states[node] = Color.GRAY;
74+
75+
for (int next : graph[node]) {
76+
77+
// If we get a `false` from any recursive call on the neighbors, we short circuit and return from there.
78+
if (!leadsToDest(graph, next, dest, states)) {
79+
return false;
80+
}
81+
}
82+
83+
// Recursive processing done for the node. We mark it BLACK
84+
states[node] = Color.BLACK;
85+
return true;
86+
}
87+
88+
private List<Integer>[] buildDigraph(int n, int[][] edges) {
89+
List<Integer>[] graph = new List[n];
90+
for (int i = 0; i < n; i++) {
91+
graph[i] = new ArrayList<>();
92+
}
93+
94+
for (int[] edge : edges) {
95+
graph[edge[0]].add(edge[1]);
96+
}
97+
98+
return graph;
99+
}
100+
}
101+
```
102+
103+
```cpp
104+
class Solution {
105+
public:
106+
static const int GRAY = 1;
107+
static const int BLACK = 2;
108+
109+
bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) {
110+
vector<vector<int>> graph = buildDigraph(n, edges);
111+
vector<int> states(n, 0);
112+
return leadsToDest(graph, source, destination, states);
113+
}
114+
115+
private:
116+
bool leadsToDest(vector<vector<int>>& graph, int node, int dest, vector<int>& states) {
117+
if (states[node] != 0) {
118+
return states[node] == BLACK;
119+
}
120+
if (graph[node].size() == 0) {
121+
return node == dest;
122+
}
123+
states[node] = GRAY;
124+
for (int next_node : graph[node]) {
125+
if (!leadsToDest(graph, next_node, dest, states)) {
126+
return false;
127+
}
128+
}
129+
states[node] = BLACK;
130+
return true;
131+
}
132+
133+
vector<vector<int>> buildDigraph(int n, vector<vector<int>>& edges) {
134+
vector<vector<int>> graph(n);
135+
for (auto& edge : edges) {
136+
graph[edge[0]].push_back(edge[1]);
137+
}
138+
return graph;
139+
}
140+
};
141+
```
142+
143+
```javascript
144+
class Solution {
145+
static GRAY = 1;
146+
static BLACK = 2;
147+
148+
/**
149+
* @param {number} n
150+
* @param {number[][]} edges
151+
* @param {number} source
152+
* @param {number} destination
153+
* @return {boolean}
154+
*/
155+
leadsToDestination(n, edges, source, destination) {
156+
const graph = this.buildDigraph(n, edges);
157+
const states = new Array(n).fill(null);
158+
return this.leadsToDest(graph, source, destination, states);
159+
}
160+
161+
/**
162+
* @param {number[][]} graph
163+
* @param {number} node
164+
* @param {number} dest
165+
* @param {(number|null)[]} states
166+
* @return {boolean}
167+
*/
168+
leadsToDest(graph, node, dest, states) {
169+
if (states[node] !== null) {
170+
return states[node] === Solution.BLACK;
171+
}
172+
if (graph[node].length === 0) {
173+
return node === dest;
174+
}
175+
states[node] = Solution.GRAY;
176+
for (const next_node of graph[node]) {
177+
if (!this.leadsToDest(graph, next_node, dest, states)) {
178+
return false;
179+
}
180+
}
181+
states[node] = Solution.BLACK;
182+
return true;
183+
}
184+
185+
/**
186+
* @param {number} n
187+
* @param {number[][]} edges
188+
* @return {number[][]}
189+
*/
190+
buildDigraph(n, edges) {
191+
const graph = Array.from({ length: n }, () => []);
192+
for (const edge of edges) {
193+
graph[edge[0]].push(edge[1]);
194+
}
195+
return graph;
196+
}
197+
}
198+
```
199+
200+
::tabs-end
201+
202+
### Time & Space Complexity
203+
204+
- Time complexity:
205+
- Typically for an entire DFS over an input graph, it takes $O(V + E)$ where $V$ represents the number of vertices in the graph and likewise, $E$ represents the number of edges in the graph. In the worst case $E$ can be $O(V^2)$ in case each vertex is connected to every other vertex in the graph. However even in the worst case, we will end up discovering a cycle very early on and prune the recursion tree. If we were to traverse the entire graph, then the complexity would be $O(V^2)$ as the $O(E)$ part would dominate. However, due to pruning and backtracking in case of cycle detection, we end up with an overall time complexity of $O(V)$.
206+
207+
- Space complexity: $O(V + E)$
208+
- Where $O(E)$ is occupied by the adjacency list and $O(V)$ is occupied by the recursion stack and the color states.
209+
210+
> Where $V$ represents the number of vertices in the graph and $E$ represents the number of edges in the graph.
211+
212+
---
213+
214+
### Why not Breadth-First Search?
215+
216+
From this [Stack Overflow](https://stackoverflow.com/questions/2869647/why-dfs-and-not-bfs-for-finding-cycle-in-graphs) answer:
217+
218+
> A BFS could be reasonable if the graph is undirected (be my guest at showing an efficient algorithm using BFS that would report the cycles in a directed graph!), where each cross edge defines a cycle (edge going from a node to an already visited node). If the cross edge is `{v1, v2}`, and the root (in the BFS tree) that contains those nodes is `r`, then the cycle is `r ~ v1 - v2 ~ r` (~ is a path, - a single edge), which can be reported almost as easily as in DFS.
219+
>
220+
> The only reason to use a BFS would be if you know your (undirected) graph is going to have long paths and small path cover (in other words, deep and narrow). In that case, BFS would require proportionally less memory for its queue than DFS' stack (both still linear of course).
221+
>
222+
> In all other cases, DFS is clearly the winner.

0 commit comments

Comments
 (0)