Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- if (topRow == bottomRow) // added after the mocking, 5/23/2017
- {
- continue;
- }
- for (int col = rightCol - 1; col >= leftCol; col--)
- {
- var current = matrix[bottomRow][col];
- spiral[index++] = current;
- }
- // go up
- if (leftCol == rightCol) // added after the mocking, 5/23/2017
- {
- continue;
- }
- for (int row = bottomRow - 1; row > topRow; row--)
- {
- var current = matrix[row][leftCol];
- spiral[index++] = current;
- }
- leftCol++;
- rightCol--;
- topRow++;
- bottomRow--;
- }
- return spiral;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement