LeetCode, leetcodeoj
Description:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
You shoshould return [1, 2, 3, 6, 9, 8, 7, 4, 5].
From the example, we can see that what we need to do is to traverse the first element of the matrix in sequence along the outer ring and print the result.
Ideas:
Obtain the length and width of the matrix. If n circles are required, n = Min (width, height)/2.
Traverse from the top left node as the Start Node, go to the rightmost last element, start to go down, go to the end to the left, and finally go up. After a circle, you need to move the coordinates to + 1.
Consider the situation that is in the middle of the matrix.
Implementation Code:
public class Solution { public IList<int> SpiralOrder(int[,] matrix) { if(matrix == null){return new List<int>();}var result = new List<int>();var rowLen = matrix.GetLength(0);var len = matrix.GetLength(1);if(rowLen == 1){for(var i =0 ;i < len; i++){result.Add(matrix[0,i]);}return result;}if(len == 1){for(var i =0 ;i < rowLen; i++){result.Add(matrix[i,0]);}return result;}var minLen = Math.Min(rowLen,len);var cycleCount = minLen % 2 == 0 ? minLen/2 : (minLen + 1) / 2;var c = 0;for(var i = 0;i < cycleCount; i++){if(c == len-c-1){for(var k = c;k < rowLen - c; k++){result.Add(matrix[k, c]);}c++;continue;}// stick row to top, column : [c,len-c-1]for(var top = c; top < len-c - 1; top++){result.Add(matrix[c,top]);}// stick column to right, row : [c,rowLen-c-1]for(var right = c; right < rowLen-c - 1; right ++){result.Add(matrix[right, len-c-1]);}// stick row to bottom, column : [len-c-1, c]for(var down = len-c -1; down > c; down --){result.Add(matrix[rowLen-c-1, down]);}// stick column to left, row : [len-c-1, c]for(var left = rowLen-c - 1; left > c; left --){result.Add(matrix[left, c]);}c++;}return result; } }
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.