算法训练营第四天 59. 螺旋矩阵 II

张开发
2026/4/17 1:16:58 15 分钟阅读

分享文章

算法训练营第四天 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; }

更多文章