54. 螺旋矩阵 23.11.28

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:

54. 螺旋矩阵 23.11.28_第1张图片

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

54. 螺旋矩阵 23.11.28_第2张图片

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100
public class Solution {
    public IList SpiralOrder(int[][] matrix) {
        List ilist= new List();
        int row = matrix.Length;
        int col = matrix[0].Length;
        bool[,] isUser = new bool[row,col];
        int dir=1;
        int m=0,n=0;
        ilist.Add(matrix[m][n]);
        isUser[0,0]=true;
        
        while (true)
        {
            switch (dir)
            {
                case 1:
                    if (n + 1 >= col) dir = 2;
                    break;
                case 2:
                    if (m + 1 >= row) dir = 3;
                    break;
                case 3:
                    if (n - 1 < 0) dir = 4;
                    break;
                case 4:
                    if (m - 1 < 0) dir = 1;
                    break;
                default:
                    break;
            }
            switch (dir)
            {
                case 1:
                    if(n + 1 =0)
                        if (isUser[m, n -1]) dir = 4;
                    break;
                case 4:
                    if(m-1>=0)
                        if (isUser[m - 1, n]) dir = 1;
                    break;
                default:
                    break;
            }
            switch (dir)
            {
                case 1:
                    if(n + 1 =0){
                        if (isUser[m, n - 1]) return ilist;
                        n--;
                    }
                    else return ilist;
                    break;
                case 4:
                    if(m-1>=0){
                        if (isUser[m - 1, n]) return ilist;
                        m--;
                    }
                    else return ilist;
                    break;
                default:
                    break;
            }
            isUser[m, n] = true;
            ilist.Add(matrix[m][n]);
        }
        return ilist;
    }
}

你可能感兴趣的:(一天二算法(LeetCode),矩阵,算法,leetcode)