Graph based Flashcards

(5 cards)

1
Q

What is the definition of Graph-Based?

A

Uses graph traversal (DFS/BFS) for connectivity.

**Use Case: ** Path finding, connected components.

Example: [Number of Islands]. Action: Verbalize use case aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the key steps in Graph-Based?

A
  1. Build graph (adjacency list/matrix).
  2. Traverse using DFS/BFS.
  3. Track visited nodes.

Action: Explain steps for [Number of Islands] aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does Graph-Based apply to [Number of Islands]?

A

Count distinct islands in grid. Use DFS to mark connected land cells.

Action: Verbalize solution logic aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the complexity and gotchas of Graph-Based?

A

Time: O(V+E) or O(m * n), Space: O(V).
Gotchas: Disconnected graphs, empty grid.

Action: List edge cases for [Number of Islands] aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Code example for Graphs (Number of islands).

A

```python
from typing import List
def num_islands(grid: List[List[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
islands = 0
def dfs(row: int, col: int) -> None:
if row < 0 or row >= rows or col < 0 or col >= cols or grid[row][col] != ‘1’:
return
grid[row][col] = ‘0’
dfs(row-1, col)
dfs(row+1, col)
dfs(row, col-1)
dfs(row, col+1)
for r in range(rows):
for c in range(cols):
if grid[r][c] == ‘1’:
islands += 1
dfs(r, c)
return islands
~~~

Action: Sketch island grid on paper.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly