Created
May 23, 2017 23:46
-
-
Save jianminchen/3df558c686f1e8c3b9553dae9c094d73 to your computer and use it in GitHub Desktop.
Leetcode 52 - spiralMatrix.cs - pass leetcode online jduge
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; | |
using System.Collections.Generic; | |
class Solution | |
{ | |
/// <summary> | |
/// Leetcode 54 | |
/// https://leetcode.com/problems/spiral-matrix/#/description | |
/// </summary> | |
public static void Main() | |
{ | |
var testcase = new int[1,2]{{1,2}}; | |
SpiralOrder(testcase); | |
} | |
/// <summary> | |
/// Need to test one row, one column | |
/// | |
/// </summary> | |
/// <param name="matrix"></param> | |
/// <returns></returns> | |
public static IList<int> SpiralOrder(int[,] matrix) | |
{ | |
int rows = matrix.GetLength(0); | |
int cols = matrix.GetLength(1); | |
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. | |
// test cases: one node in the array, one row, one column | |
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 (bottomRow == topRow) | |
{ | |
continue; | |
} | |
for (int col = rightCol - 1; col >= leftCol; col--) | |
{ | |
var current = matrix[bottomRow, col]; | |
spiral[index++] = current; | |
} | |
// go up | |
if (leftCol == rightCol) | |
{ | |
continue; | |
} | |
for (int row = bottomRow - 1; row > topRow; row--) | |
{ | |
var current = matrix[row, leftCol]; | |
spiral[index++] = current; | |
} | |
leftCol++; | |
rightCol--; | |
topRow++; | |
bottomRow--; | |
} | |
return new List<int>(spiral); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment