[Solution] Espiral matrix print | Amazon Interview Question
Here's your coding interview problem for today. This problem was asked by Amazon.
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
You should print out the following:
1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12
Idea behind the solution
First and foremost, assumptions has been made: the input will always be either a number or one of the basic math operations and each node of the tree will have either 2 or none childrens.
This problem can be done recursively. In the recursive function we just need to check if we have a leaf (no left and right children). If that is the case, assume we have a number and return it, otherwise, just update the current node's val by calling the same function for both left and right children.
Carefull with the call stack limit, which may not allow to run this code for a deep tree. This code may be improved by coding an iterative version.
Please check the main.js snippet for the solution.
This solution originally posted at: Github by @Murillo2380