Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,17 @@ Often with recursive functions, we require a driver function to set-up certain v
Here is the completed code:

```python
def DFSUtil(self, v, visited):
visited[v] = True
print(v, end = ' ')
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)
def DFSUtil(self, v, visited):
visited[v] = True
print(v, end = ' ')

for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)

def DFS(self, v):
visited = [False] * (len(self.graph))
self.DFSUtil(v, visited)
def DFS(self, v):
visited = [False] * (len(self.graph))
self.DFSUtil(v, visited)

```

Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ To explain this, we will have to delve into the code of DFS.

```Python
def DFSUtil(self, v, visited):
visited[v] = True
print(v, end = ' ')
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)
visited[v] = True
print(v, end = ' ')
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)

def DFS(self, v):
visited = [False] * (len(self.graph))
self.DFSUtil(v, visited)
visited = [False] * (len(self.graph))
self.DFSUtil(v, visited)
```

###What is the time complexity?
Expand All @@ -31,11 +31,11 @@ Well, as it turns out, the while loop is actually hidden in the code above. Ins

```python
if visited[i] == False:
self.DFSUtil(i, visited)
self.DFSUtil(i, visited)
```

Therefore, the recursion occurs in O(n) time, where n is the number of vertices in the graph. Thus, when we combine the time complexities for recursion and the for loop, we again get O(V + E).

### Adjacency List vs Adjacency Matrix

We will get the same time complexity we got for BFS for the adjacency list and the adjacency matrix implementation of DFS. And the reason for that is the same reason given for BFS. If you were to use an adjacency matrix, then you will have to iterate V^2 times, but in an adjacency list, you will only have to do it V + E times. Thus, adjacency list = O(V + E) and adjacency matrix is O(V^2).
We will get the same time complexity we got for BFS for the adjacency list and the adjacency matrix implementation of DFS. And the reason for that is the same reason given for BFS. If you were to use an adjacency matrix, then you will have to iterate V^2 times, but in an adjacency list, you will only have to do it V + E times. Thus, adjacency list = O(V + E) and adjacency matrix is O(V^2).