Created
May 24, 2017 00:01
-
-
Save jianminchen/d9b257d9882bed9cee55a9d8c75db4be to your computer and use it in GitHub Desktop.
Use leetcode 52 online judge to help, find the bugs in the code. Runtime error for one row or one column test case. Add checking for one row and one col.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment