Problem · Matrix

Spiral Matrix with Obstacles

Learn this problem
MediumTemu logoTemuFULLTIMEONSITE INTERVIEW

Problem statement

You are given a nonempty rectangular integer matrix grid. Every cell initially contains either 0, meaning it is fillable, or -1, meaning it is an obstacle.

Starting at the top-left cell and moving right, write consecutive positive integers into fillable cells. Before each move, inspect the next cell:

  • If it is inside the matrix, is not an obstacle, and has not yet been numbered, move into it.
  • Otherwise, rotate clockwise and inspect the next direction. Continue rotating, up to all four directions, until a valid move is available.

Obstacle cells remain -1. The input guarantees that the top-left cell is fillable and that this clockwise right-turn walk reaches every fillable cell. Stop after numbering every fillable cell, then return grid.

Function

fillSpiralWithObstacles(grid: int[][]) → int[][]

Examples

Example 1

grid = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]return = [[1,2,3,4],[10,11,12,5],[9,8,7,6]]

With no obstacles, the matrix is numbered in the usual clockwise spiral order.

Example 2

grid = [[0,0,0,0],[0,0,-1,0],[0,0,0,0],[0,0,0,0]]return = [[1,2,3,4],[12,13,-1,5],[11,14,15,6],[10,9,8,7]]

The obstacle remains -1. Near the center, the traversal may reject several directions before finding the next open, unnumbered cell.

Example 3

grid = [[0,-1,0],[0,-1,0],[0,0,0]]return = [[1,-1,7],[2,-1,6],[3,4,5]]

The first move to the right is blocked, so the traversal rotates downward and later reaches the right column from below.

Constraints

  • 1 <= grid.length and 1 <= grid[0].length.
  • grid is rectangular.
  • grid.length * grid[0].length <= 100000.
  • Every initial cell is either 0 or -1.
  • grid[0][0] == 0.
  • The clockwise right-turn walk reaches every fillable cell.
drafts saved locally
public int[][] fillSpiralWithObstacles(int[][] grid) {
    // Write your code here.
}
grid[[0,0,0,0],[0,0,0,0],[0,0,0,0]]
expected[[1,2,3,4],[10,11,12,5],[9,8,7,6]]
checking account