Facebook Pixel

Spiral Matrix Pathfinder

JavaScript
medium
45 mins

Given a 2D matrix where some cells contain obstacles (marked as -1), traverse the matrix in a spiral pattern starting from the top-left corner. Collect all non-obstacle values in the order they are visited.

Function Signature

function spiralMatrixPathfinder(matrix) { // Your code here }

Parameters

  • matrix: A 2D array where:
    • Regular cells contain integers (values to collect)
    • Obstacle cells contain -1 (to be avoided)

Return Value

  • Return an array of integers representing the values collected in spiral order, excluding obstacles.

Examples

Input: matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Input: matrix = [ [1, -1, 3], [4, 5, 6], [7, 8, 9] ] Output: [1, 3, 6, 9, 8, 7, 4, 5]
Input: matrix = [ [1, 2], [3, 4] ] Output: [1, 2, 4, 3]

Spiral Pattern

The spiral traversal follows this pattern:

  • Right: Top row from left to right
  • Down: Right column from top to bottom
  • Left: Bottom row from right to left
  • Up: Left column from bottom to top
  • Repeat, moving inward each time

Rules

  • Obstacle Avoidance: Skip any cell with value -1
  • Boundary Checking: Stay within matrix boundaries
  • Visited Tracking: Don’t revisit already visited cells
  • Spiral Direction: Always follow the spiral pattern (right → down → left → up)

Constraints

  • (1 \leq \text{matrix.length} \leq 100)
  • (1 \leq \text{matrix[i].length} \leq 100)
  • All rows have the same length
  • Matrix values are integers (including -1 for obstacles)
  • Matrix is not empty

Algorithm

  1. Use four pointers (top, bottom, left, right) to track the current boundaries.
  2. Use a visited array to avoid revisiting cells.
  3. Traverse in spiral order:
    • Right: Traverse the top row from left to right.
    • Down: Traverse the right column from top to bottom.
    • Left: Traverse the bottom row from right to left.
    • Up: Traverse the left column from bottom to top.
  4. Collect non-obstacle values (value != -1) in traversal order.
  5. Update boundaries after completing each direction.

Test Cases

  • Regular matrices without obstacles
  • Matrices with obstacles blocking paths
  • Single row or single column matrices
  • Empty matrices
  • Matrices with all obstacles
  • Edge cases with minimum size matrices

Companies:

google
meta
microsoft
amazon
uber
adobe

Solve Similar questions 🔥