Skip to content

Seeking Safety

Raymond Chen edited this page Oct 6, 2024 · 1 revision

Unit 11 Session 1 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 30 mins
  • 🛠️ Topics: Grid Traversal, Matrix Navigation

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?
  • Can I move diagonally?
    • No, only horizontal and vertical adjacent moves are allowed.
  • What should I return if no moves are safe?
    • Return an empty list.
  • What is the size of the grid?
    • The grid can be any size, but it will always be a valid matrix.
  • Can the grid contain other values besides 1 and 0?
    • No, only 1s and 0s are in the grid.
HAPPY CASE
Input: position = (3, 2), 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: [(3, 1), (3, 3), (2, 2)]
Explanation: The cell to the left, right, and above of (3, 2) are safe. The one below is not safe.

EDGE CASE
Input: position = (0, 1), 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: []
Explanation: All the cells adjacent to (0, 1) are unsafe or out of bounds.

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:

  • Matrix Navigation: This problem involves moving in a grid and checking neighboring cells.
  • Bounds Checking: Ensure that any movement remains within the grid's valid indices.
  • Adjacency Checks: Validate moves based on adjacent cells that have specific properties.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: From the given position, check all four directions (up, down, left, right) to see if the adjacent cells are within the grid bounds and marked as safe (i.e., 1).

1) Get the current row and column from the input position.
2) Set up a list of valid movement directions: up, down, left, right.
3) Initialize an empty list to store valid next moves.
4) For each direction:
    a) Calculate the new position by adding the direction's offsets to the current position.
    b) Check if the new position is within the grid bounds and if the new cell is marked safe (value 1).
    c) If both conditions are satisfied, add the new position to the list of valid moves.
5) Return the list of valid moves.

⚠️ Common Mistakes

  • Forgetting to check grid boundaries can result in out-of-bounds errors.
  • Failing to account for cases where no valid moves exist.

4: I-mplement

Implement the code to solve the algorithm.

def next_moves(position, grid):
    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 and is safe (i.e., grid[new_row][new_col] == 1)
        if 0 <= new_row < rows and 0 <= new_col < cols and grid[new_row][new_col] == 1:
            valid_moves.append((new_row, new_col))
    
    return valid_moves

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: position = (3, 2), 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: [(3, 1), (3, 3), (2, 2)]
  • Watchlist:
    • d_row, d_col values during iteration
    • new_row, new_col values and their validity
    • grid[new_row][new_col] values to check safety

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(1) because we only check four neighboring cells regardless of the grid size.
  • Space Complexity: O(1) as no additional space is used outside of the list for storing valid moves.
Clone this wiki locally