算法训练营第四天 59. 螺旋矩阵 II
本题关键还是在转圈的逻辑,在二分搜索中提到的区间定义
越来越难了,理解需要的时间更多了需要更多的思考
#include <stdlib.h> int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) { *returnSize = n; *returnColumnSizes = (int*)malloc(sizeof(int) * n); for (int i = 0; i < n; ++i) { (*returnColumnSizes)[i] = n; } int** matrix = (int**)malloc(sizeof(int*) * n); for (int i = 0; i < n; ++i) { matrix[i] = (int*)malloc(sizeof(int) * n); } int top = 0; int bottom = n - 1; int left = 0; int right = n - 1; int num = 1; int total = n * n; while (num <= total) { for (int c = left; c <= right && num <= total; ++c) { matrix[top][c] = num++; } top++; for (int r = top; r <= bottom && num <= total; ++r) { matrix[r][right] = num++; } right--; for (int c = right; c >= left && num <= total; --c) { matrix[bottom][c] = num++; } bottom--; for (int r = bottom; r >= top && num <= total; --r) { matrix[r][left] = num++; } left++; } return matrix; }