leetcode day23 54 螺旋矩阵

54 螺旋矩阵

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

示例 1:

leetcode day23 54 螺旋矩阵_第1张图片

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

示例 2:

leetcode day23 54 螺旋矩阵_第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]

解题思路:设四个变量top,bottom,left,right,分别为上下左右

最外层循环条件为left<=right&&top<=bottom,保证最后同一行和同一列仍然可以顺时针遍历。分四次循环遍历,从左往右,从上往下,从右往左,从下往上。每次循环结束后更新四个变量其中一个的值,注意考虑越界情况。

二维数组行m=matrixSize,列n=matrixColSize[0]

int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize) {
    int m=matrixSize,n=matrixColSize[0];//二维数组的行列
    int *a=(int *)malloc(sizeof(int)*m*n);
    *returnSize=0;
    int left=0,right=n-1,top=0,bottom=m-1;
    int i,j;
    //上-->下开始左开右闭
    while(left<=right&&top<=bottom){
        for(j=left;j<=right;j++){
            a[(*returnSize)++]=matrix[top][j];
        }
        top++;
        if(top>bottom)break;
        for(i=top;i<=bottom;i++){
            a[(*returnSize)++]=matrix[i][right];
        }
        right--;
        if(left>right)break;
        for(j=right;j>=left;j--){
              a[(*returnSize)++]=matrix[bottom][j];
        }
        bottom--;
        if(top>bottom)break;
        for(i=bottom;i>=top;i--){
            a[(*returnSize)++]=matrix[i][left];
        }
        left++;
        if(left>right)break;
    }
    return a;
}

你可能感兴趣的:(leetcode,矩阵,c#)