Skip to content

Instantly share code, notes, and snippets.

@hueitan
Created May 10, 2015 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hueitan/51c798e0bd5c55c09a8c to your computer and use it in GitHub Desktop.
Save hueitan/51c798e0bd5c55c09a8c to your computer and use it in GitHub Desktop.
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