这道题跟我昨天发布的那道题一模一样,只需要注意这个矩阵是n*n。
文章代码如下:
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) { int** array = (int**)malloc(sizeof(int*) * n); *returnColumnSizes = (int*)malloc(sizeof(int) * n); *returnSize = n; int curnum = 1; for(int i =0 ; i<n ; i++) { array[i] = (int*)malloc(sizeof(int) * n); memset(array[i] , 0 , sizeof(int)*n); (*returnColumnSizes)[i] = n; } int i =0 ,j =0; for(i=0,j=0 ; i<n && j<n ; i++,j++) { int i_t = i, j_t = j; while(j_t < n) { array[i_t][j_t] = curnum; curnum++; j_t++; } j_t--; i_t++; while(i_t < n ) { array[i_t][j_t] = curnum; curnum++; i_t++; } i_t--; j_t--; while(j_t >= j) { array[i_t][j_t] = curnum; curnum++; j_t--; } j_t++; i_t--; while(i_t > i) { array[i_t][j_t] = curnum; curnum++; i_t--; } n--; } return array; }