1. 程式人生 > >LeetCode 59. 螺旋矩陣 II Spiral Matrix II(C語言)

LeetCode 59. 螺旋矩陣 II Spiral Matrix II(C語言)

題目描述:

給定一個正整數 n,生成一個包含 1 到 n2 所有元素,且元素按順時針順序螺旋排列的正方形矩陣。

示例:

輸入: 3
輸出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

題目解答:

方法1:遍歷

按順序放置數字,上邊,右邊,下邊,左邊。
執行時間0ms,程式碼如下。

/**
 * Return an array of arrays.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int
** generateMatrix(int n) { int i = 0; int** result = (int**)malloc(n * sizeof(int*)); for(i = 0; i < n; i++) result[i] = (int*)malloc(n * sizeof(int)); int t = 1, row_start = 0, col_start = 0, row_end = n, col_end = n; int end = n * n; while(t <= end) { for
(i = col_start; i < col_end; i++) result[row_start][i] = (t++); row_start++; for(i = row_start; i < row_end; i++) result[i][row_end - 1] = (t++); col_end--; for(i = col_end - 1; i >= col_start; i--) result[row_end - 1][i] =
(t++); row_end--; for(i = row_end - 1; i >= row_start; i--) result[i][col_start] = (t++); col_start++; } return result; }