Largest Safe Zone - codepath/compsci_guides GitHub Wiki
Unit 11 Session 1 Standard (Click for link to problem statements)
Problem Highlights
- 💡 Difficulty: Medium
- ⏰ Time to complete: 45 mins
- 🛠️ Topics: Grid Traversal, Depth-First Search, Connected Components
1: U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
- What is a ""connected"" group of safe zones?
- A group of adjacent
1
s (safe zones) that are connected horizontally or vertically.
- A group of adjacent
- Can safe zones be connected diagonally?
- No, only horizontal and vertical connections are valid.
- What should I return if the grid has no safe zones?
- Return
0
as there are no connected safe zones.
- Return
HAPPY CASE
Input: grid = [
[0, 0, 0, 1, 1],
[0, 0, 0, 1, 1],
[1, 1, 1, 0, 0],
[1, 1, 1, 1, 0],
[0, 0, 0, 1, 0]
]
Output: 8
Explanation: The largest connected component of safe zones has size 8.
EDGE CASE
Input: grid = [
[0, 0],
[0, 0]
]
Output: 0
Explanation: There are no safe zones, so the output is 0.
2: M-atch
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Grid Traversal problems, we want to consider the following approaches:
- Graph Representation: Each cell is a node, and edges exist between adjacent safe zones (
1
s). - Depth-First Search (DFS): DFS can be used to explore connected components of safe zones.
- Breadth-First Search (BFS): BFS could also be used for exploring the grid, though DFS is easier for recursive exploration.
3: P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: For each cell in the grid, if the cell is a safe zone (1
) and has not been visited, perform DFS to explore all connected safe zones. Keep track of the size of each connected component and update the largest size found.
1) Define a helper function `next_moves` that returns valid adjacent cells that are safe zones and unvisited.
2) Define a recursive DFS function `explore_safe_zone` that explores the connected component starting from a given safe zone.
3) Iterate over each cell in the grid:
a) If the cell is a safe zone (`1`) and has not been visited, call `explore_safe_zone`.
b) Keep track of the size of the connected component and update the largest size found.
4) Return the largest connected component size.
⚠️ Common Mistakes
- Forgetting to mark zones as visited can lead to infinite loops.
- Failing to handle edge cases such as grids with no safe zones.
4: I-mplement
Implement the code to solve the algorithm.
# Helper function to find valid next moves
def next_moves(position, grid, visited):
row, col = position
rows = len(grid)
cols = len(grid[0])
# Define directions for moving up, down, left, and right
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# List to hold the valid next moves
valid_moves = []
# Check each direction
for d_row, d_col in directions:
new_row, new_col = row + d_row, col + d_col
# Ensure new position is within the grid bounds, is a safe zone, and not visited
if 0 <= new_row < rows and 0 <= new_col < cols and grid[new_row][new_col] == 1 and (new_row, new_col) not in visited:
valid_moves.append((new_row, new_col))
return valid_moves
# Recursive DFS function to explore the connected component
def explore_safe_zone(row, col, grid, visited):
visited.add((row, col))
size = 1 # This cell itself contributes 1 to the size
# Get valid next moves and recursively explore them
for next_row, next_col in next_moves((row, col), grid, visited):
size += explore_safe_zone(next_row, next_col, grid, visited)
return size
# Main function to find the largest safe zone
def largest_safe_zone(grid):
rows, cols = len(grid), len(grid[0])
visited = set()
largest_area = 0
# Iterate through each cell in the grid
for row in range(rows):
for col in range(cols):
# If we find a safe zone and it hasn't been visited yet, explore it
if grid[row][col] == 1 and (row, col) not in visited:
# Perform recursive DFS to find the size of this connected component
size_of_safe_zone = explore_safe_zone(row, col, grid, visited)
# Update the largest area if necessary
largest_area = max(largest_area, size_of_safe_zone)
return largest_area
5: R-eview
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example 1:
- Input: grid = [ [0, 0, 0, 1, 1], [0, 0, 0, 1, 1], [1, 1, 1, 0, 0], [1, 1, 1, 1, 0], [0, 0, 0, 1, 0] ]
- Expected Output: 8
- Watchlist:
- Ensure
visited
is updated correctly during DFS. - Check that the largest connected component is calculated correctly.
- Verify that no safe zones are revisited.
- Ensure
6: E-valuate
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume m
is the number of rows and n
is the number of columns in the grid.
- Time Complexity:
O(m * n)
because every cell is visited once during DFS. - Space Complexity:
O(m * n)
due to the recursive DFS call stack and thevisited
set.