Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
spiral order (clockwise from top left) -

It's from others.

function spiralMatrix(matrix) {

  var i;
  var top = 0;
  var left = 0;
  var bottom = matrix.length;
  var right = matrix[0].length;
  var o = '';
  
  while (top < bottom && left < right) {

    //print top 
    for (i = left; i < right; i += 1) {
      o += (matrix[top][i]);
    }
    top++;

    //print right column
    for (i = top; i < bottom; i += 1) {
      o += (matrix[i][right - 1]);
    }
    right--;

    if (top < bottom) {
      //print bottom
      for (i = right - 1; i >= left; i -= 1) {
        o += (matrix[bottom - 1][i]);
      }
      bottom--;
    }

    if (left < right) {
      //print left column
      for (i = bottom - 1; i >= top; i -= 1) {
        o += (matrix[i][left]);
      }
      left++;
    }
  }
  
  return o;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.