Spiral_Matrix_II.png
/*
* Abstract: Exactly the same idea as #54
*/
#define DIR_RIGHT 0
#define DIR_DOWN 1
#define DIR_LEFT 2
#define DIR_UP 3
void next(int *i, int *j, int *dir, int *right_barr, int *bottom_barr, int *left_barr, int *top_barr) {
if (*dir == DIR_RIGHT) {
if (*j == *right_barr) {
(*right_barr)--;
(*i)++;
*dir = DIR_DOWN;
} else {
(*j)++;
}
} else if (*dir == DIR_DOWN) {
if (*i == *bottom_barr) {
(*bottom_barr)--;
(*j)--;
*dir = DIR_LEFT;
} else {
(*i)++;
}
} else if (*dir == DIR_LEFT) {
if (*j == *left_barr) {
(*left_barr)++;
(*i)--;
*dir = DIR_UP;
} else {
(*j)--;
}
} else if (*dir == DIR_UP) {
if (*i == (*top_barr)) {
(*top_barr)++;
(*j)++;
*dir = DIR_RIGHT;
} else {
(*i)--;
}
}
}
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){
int **matrix = (int**)malloc(n * sizeof(*matrix));
*returnColumnSizes = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
matrix[i] = (int*)malloc(n * sizeof(int));
(*returnColumnSizes)[i] = n;
}
*returnSize = n;
int right_barr = n - 1, bottom_barr = n - 1, left_barr = 0, top_barr = 1;
int i = 0, j = 0, dir = 0, val = 0, totalSize = n * n;
while (val < totalSize) {
val++;
matrix[i][j] = val;
next(&i, &j, &dir, &right_barr, &bottom_barr, &left_barr, &top_barr);
}
return matrix;
}
网友评论