LeeCode-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 ]
]

/**
 * Return an array of arrays.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int** generateMatrix(int n) {
        int **Maxtrix;
    
    Maxtrix=(int **)malloc(n*sizeof(int*));
    for(int k=0;k<n;k++)
        Maxtrix[k]=(int *)malloc(sizeof(int)*n);

    int number = 1;
    int top = 0;
    int bottom = n-1;
    int left = 0;
    int right = n-1;

    int i,j;
    while(number<=n*n)
    {
        for(i=left;i<=right;i++)
            Maxtrix[top][i]=number++;
        top++;

        for(i=top;i<=bottom;i++)
            Maxtrix[i][right]=number++;
        right--;

        for(i=right;i>=left;i--)
            Maxtrix[bottom][i]=number++;
        bottom--;

        for(i=bottom;i>=top;i--)
            Maxtrix[i][left]=number++;
        left++;

    }
    return Maxtrix;
}


發佈了307 篇原創文章 · 獲贊 65 · 訪問量 61萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章