Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 23, 2017 22:03
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 jianminchen/913a95ea7d11ce1da66fb2a02bb08ec1 to your computer and use it in GitHub Desktop.
Save jianminchen/913a95ea7d11ce1da66fb2a02bb08ec1 to your computer and use it in GitHub Desktop.
Spiral array - practice 2017 May
using System;
class Solution
{
// Spiral array -
public static void Main()
{
var testcase = new int[4][];
testcase[0] = new int[] {1, 2, 3, 4 };
testcase[1] = new int[] {12, 13, 14, 5 };
testcase[2] = new int[] {11, 16, 15, 6 };
testcase[3] = new int[] {10, 9, 8, 7 };
testcase = new int[1][];
testcase[0] = new int[] { 1 };
var result = SpiralCopy(testcase);
}
public static int[] SpiralCopy(int[][] matrix)
{
int rows = matrix.Length;
int cols = matrix[0].Length;
int total = rows * cols;
var spiral = new int[total];
int index = 0;
int leftCol = 0;
int rightCol = cols - 1;
int topRow = 0;
int bottomRow = rows - 1;
// the idea is to simplify the while loop - one variable checking, check the length of spiral
// array intead of compared to the start position of spiral layer.
while (index < total)
{
// top row - go right,
for (int col = leftCol; col <= rightCol; col++)
{
var current = matrix[topRow][col];
spiral[index++] = current;
}
// right col - go down
for (int row = topRow + 1; row <= bottomRow; row++)
{
var current = matrix[row][rightCol];
spiral[index++] = current;
}
// go left
for (int col = rightCol - 1; col >= leftCol; col--)
{
var current = matrix[bottomRow][col];
spiral[index++] = current;
}
// go up
for (int row = bottomRow - 1; row > topRow; row--)
{
var current = matrix[row][leftCol];
spiral[index++] = current;
}
leftCol++;
rightCol--;
topRow++;
bottomRow--;
}
return spiral;
}
}
@jianminchen
Copy link
Author

Julia noticed that there are a bug line 53 - line 58. The array index out-of-range error. One row is the special test case, need to check if(topRow == bottomRow), and also one column checking before left col handling from line 60 - line 65.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment