LeetCode-54&59.Spiral Matrix

来源:互联网 发布:中日高铁争夺战 知乎 编辑:程序博客网 时间:2024/05/21 11:34

54 https://leetcode.com/problems/spiral-matrix/

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 should return [1,2,3,6,9,8,7,4,5].

 public IList<int> SpiralOrder(int[,] matrix)        {            IList<int> res = new List<int>();            int m = (int)matrix.GetLongLength(0);            int n = (int)matrix.GetLongLength(1);            int len = m * n, i = 0, j = 0, begin = 0;            while (len > 0)            {                if (len == 1)                {                    res.Add(matrix[i, j]);                    break;                }                while (len > 0 && j < n - 1)                {                    res.Add(matrix[i, j++]);                    len--;                }                while (len > 0 && i < m - 1)                {                    res.Add(matrix[i++, j]);                    len--;                }                while (len > 0 && j > begin)                {                    res.Add(matrix[i, j--]);                    len--;                }                while (len > 0 && i > begin)                {                    res.Add(matrix[i--, j]);                    len--;                }                begin++;                m--;                n--;                i = j = begin;            }            return res;        }

59 https://leetcode.com/problems/spiral-matrix-ii/

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]

public int[,] GenerateMatrix(int n)     {        int i = 0, j = 0, k = 0, begin = 0, len = n * n;        int[,] res = new int[n, n];        while (k < len)        {            if (k == len-1)            {                res[i, j] = len;                break;            }            while (k < len && j < n - 1)                res[i, j++] = ++k;            while (k < len && i < n - 1)                res[i++, j] = ++k;            while (k < len && j > begin)                res[i, j--] = ++k;            while (k < len && i > begin)                res[i--, j] = ++k;                        begin++;            n--;            i = j = begin;        }        return res;    }



0 0