Spiral traversal of a matrix - recursive solution in JavaScript

spiral matrix
reverse spiral matrix
javascript create matrix array
3 3 matrix in javascript
matrix traversal
spiral pattern in c without using array
spiral matrix traversal leetcode
outward spiral matrix

I'm trying to come up with a solution that takes in a matrix like this:


and returns an array traversing the array as a spiral, so in this example: [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]

I'm having trouble getting this recursive solution to work, in which the result array takes the first array, the final elements of the rest of the arrays, the bottom array in reverse order, and then the first elements of the middle arrays, and then reforms the array without that outer "shell" so that it can be recursively called on what's left until there's an array of one element in the center or a 2x2 matrix (my base cases, although the latter might not be necessary...)

My solution, which doesn't work, is as follows. Any suggestions on how I can make this work?

var spiralTraversal = function(matriks){
  var result = [];
    var goAround = function(matrix) {
        var len = matrix[0].length;
        if (len === 1) {
            return result;
        if (len === 2) {
            result.push(matrix[1][1], matrix[1][0]);
            return result;
        if (len > 2) {
            // right
            // down
            for (var j=1; j < matrix.length - 1; j++) {
                result.push(matrix[j][matrix.length -1]);
            // left
            for (var l=matrix.length - 2; l > 0; l--) {
                result.push(matrix[matrix.length - 1][l]);
            // up
            for (var k=matrix.length -2; k > 0; k--) {
        // reset matrix for next loop
        var temp = matrix.slice();
        for (var i=0; i < temp.length - 1; i++) {
            temp[i] = temp[i].slice(1,-1);

Print a given matrix in spiral form, In each outer loop traversal print the elements of a square in clockwise manner. Algorithm: create a recursive function that takes a matrix and some variables  Spiral traversal of a matrix - recursive solution in JavaScript Tag: javascript , arrays , algorithm , recursion , matrix I'm trying to come up with a solution that takes in a matrix like this:

🌀 Spiral Array (ES6)

ES6 allows us to keep it simple:

function spiral(matrix) {
    const arr = [];

    while (matrix.length) {
            ...matrix.map(a => a.pop()),
            ...matrix.map(a => a.shift()).reverse()
    return arr;

Create a NxN Matrix Spiral with JavaScript, Firstly, let's have some analysis on our 4x4 example. Obviously, we will have a 2-​dimension array. Then, in order to fill in the number for the correct rows and  We have seen recursive and iterative solutions using two stacks and an approach using one stack and one queue.In this post, a solution with one deque is discussed. The idea is to use a direction variable and decide whether to pop elements from the front or from the rear based on the value of this direction variable.

This solution is for any kind of matrix (m * n), not just square(m * m). Below example takes 5*4 matrix and prints in spiral format.

var matrix =  [[1,2,3,4], [14,15,16,5], [13,20,17,6], [12,19,18,7], [11,10,9,8]];

var row = currentRow = matrix.length, column = currentColumn = matrix[0].length;

while(currentRow > row/2 ){

  // traverse row forward
  for(var i = (column - currentColumn); i < currentColumn ; i++) { console.log(matrix[row - currentRow][i]); }

  // traverse column downward
  for(var i = (row - currentRow + 1); i < currentRow ; i++) { console.log(matrix[i][currentColumn - 1]) }

  // traverse row backward
  for(var i = currentColumn - 1; i > (column - currentColumn) ; i--) { console.log(matrix[currentRow - 1][i - 1]); }

  // traverse column upward
  for(var i = currentRow - 1; i > (row - currentRow + 1) ; i--) { console.log(matrix[i - 1][column - currentColumn]) }


Print a matrix in spiral order, The spiral begins at the top left of the matrix and loops around it towards the center in a clockwise pattern. Below is a clever algorithm that uses recursion to print  Given a matrix mat[][] of size N x N, the task is to traverse the matrix Diagonally in Bottom-up fashion using recursion. Diagonally Bottum-up Traversal: Traverse the major-diagonal of the matrix. Traverse the bottom diagonal to the major-diagonal of the matrix. Traverse the up diagonal to the major-diagonal of the matrix.

Spirally Traversing a Two-Dimensional Array in JavaScript, This is a way to traverse a two-dimensional array (or a matrix) from the top left, This solution is inspired by functional programming and it uses tail recursion. be a matrix array ", css); return -1; } } /* * Tail recursive implementation of the matrix spirally, clockwise rotation */ function spiral(matrix, result) { if  Given a matrix mat[][] of size M*N. Traverse and print the matrix in spiral form. Input: The first line of the input contains a single integer T, denoting the number of test cases. Then T test cases follow. Each testcase has 2 lines. First line contains M and N respectively separated by a space. Second line contains M*N values separated by spaces.

Recursive Solution:

Instead of going around, I just go over the top row, and the rightmost column, then recursively call the function on the "reversed" matrix.

var input = [
                [ 1, 2, 3, 4], 
                [ 5, 6, 7, 8], 
                [ 9,10,11,12], 

let spiral = (mat) => {
    if(mat.length && mat[0].length) {
        mat[0].forEach(entry => { console.log(entry)})
        mat.forEach(item => {

let reverseMatrix = (mat) => { 
    mat.forEach(item => { 
    return mat; 

console.log("Clockwise Order is:")

Spiral traversal of a matrix, Spiral traversal of a matrix - recursive solution in JavaScript I'm trying to come up with a solution that takes in a matrix like this: [[1,2,3,4], [5,6,7,8]  In a single loop we will print one complete circle of elements. Hence we will have 4 loops inside a bigger loop to print the 1. Top Row from Left to Right 2. Last Column from Top to bottom 3. Last Row from Right to Left 4. First Column Bottom to Top So first pass (of outer loop, which has the above 4 loops)

Spiral Matrix, Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. Example 1: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1  Traversing a matrix in spiral order the spiral order of given matrix: Solution: Searching sizeof Sliding Window Sorting Stack String TimeComplexity Traversal

Print Matrix in Spiral order using Recursion., Print Matrix in Spiral order using Recursion. Print elements of the matrix in spiral order in Recursive way. Print two-dimensional array in spiral  Method 1 (Recursive) This problem can be seen as an extension of the level order traversal post. To print the nodes in spiral order, nodes at different levels should be printed in alternating order.

Print Matrix in Spiral Order, Given a MxN matrix, print matrix in spiral order. To maintain the spiral order four loops are used, each for top, right, bottom and left corner of the matrix. We can also achieve this easily with the help of recursion. using C, C++, Java, Python, JavaScript, C#, PHP and many more popular programming languages. Like us? Given a 2D array, print it in spiral form. See the following examples. Approach: The above problem can be solved using four for loops which prints all the elements. Every for loop defines a single direction movement along with the matrix. The first for loop represents the movement from left to right, whereas the second crawl represents the

  • Tell me, is it possible to implement this in PHP?
  • @Lior Elrom the code is crisp and concise. Never thought spread operator can be used for this task.
  • there is "undefined" exception if you try it on matrix size N*M (5*4) for example. surround the loop with try and catch are solving that. anyway this is beautiful solution.
  • @MatanTubul good point. Instead of using try catch, replace ...matrix.pop().reverse() with ...(matrix.pop() || []).reverse() to account for non-array result.
  • Thank you. I made the first suggested change but I'm still getting an error. jsfiddle.net/vdn9ygae
  • @zahabba: OK, I looked more closely and found a few more things :-)