Walk a Matrix Coding Interview Question | Skilled.dev
Interview Question

# Walk a Matrix

You are given a `matrix` represented by an `r x c` two-dimensional array of integers. Starting at the root `matrix[row = 0][column = 0]` and walking from the perimeter of the matrix towards the center, you want to touch each element once in the matrix by traversing it clockwise in spiral order. Return a 1-dimensional array of all the elements from the matrix in the order you visited them.

Write a function `walkMatrix` that takes an `r x c` 2D array and returns a 1D array of all the elements in the matrix printed in clockwise order.

Note: Do not consider the result array when calculating your space complexity.

`` ``

## Breakdown

1. You can do this in linear time O(n) and only need to visit each cell once.

2. You may be tempted to use an additional data structure which would add an additional linear O(n) space. Based on the board dimensions and location, you can actually solve this with constant space O(1).

3. Ensure you handle your indexes well and don't have off-by-one when tracking or let them bleed into cells you have already visited.

4. Does your solution handle any board dimension `r x c`? The input can be a square, vertical rectangle, or horizontal rectangle.

5. Does your solution handle an empty matrix `[[]]` `0 x 0` input?

6. Does your solution handle a `1 x c` and `r x 1` input correctly without repeating values?

Test Results

Run your code and see results here...

### Walk a Matrix

You are given a `matrix` represented by an `r x c` two-dimensional array of integers. Starting at the root `matrix[row = 0][column = 0]` and walking from the perimeter of the matrix towards the center, you want to touch each element once in the matrix by traversing it clockwise in spiral order. Return a 1-dimensional array of all the elements from the matrix in the order you visited them.

Write a function `walkMatrix` that takes an `r x c` 2D array and returns a 1D array of all the elements in the matrix printed in clockwise order.

Note: Do not consider the result array when calculating your space complexity.

`` ``