leetcode 螺旋矩阵
顺时针螺旋的顺序读取矩阵中的元素。
代码:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
int *result = malloc(sizeof(int) * (matrixSize * (*matrixColSize)));
memset(result, 0, matrixSize * (*matrixColSize));
*returnSize = matrixSize * (*matrixColSize);
int cur = 0;
int row = 0;
int col = 0;
int i = 0, j = 0;
while (row < matrixSize && col < *matrixColSize) {
while (j < (*matrixColSize - (col / 2))) {
// printf("%d ", matrix[i][j]);
result[cur++] = matrix[i][j];
j++;
}
j--; // 退出循坏是多加了1
row++; // 遍历完一行
if (row >= matrixSize) break;
i++;
while (i < (matrixSize - (row / 2))) {
// printf("%d ", matrix[i][j]);
result[cur++] = matrix[i][j];
i++;
}
i--;
col++;
if (col >= *matrixColSize) break;
j--;
while (j >= (col / 2)) {
// printf("%d ", matrix[i][j]);
result[cur++] = matrix[i][j];
j--;
}
j++;
row++;
if (row >= matrixSize) break;
i--;
while (i >= (row / 2)) {
// printf("%d ", matrix[i][j]);
result[cur++] = matrix[i][j];
i--;
}
i++;
col++;
if (col >= *matrixColSize) break;
j++;
}
return result;
}
读取矩阵时,只要有4个:
-
行左边不变,列坐标增加(即每行从左往右遍历矩阵)
-
列坐标不变,行坐标增加(即每列从上往下遍历矩阵)
-
行坐标不变,列坐标减少(即每行从右往左遍历矩阵)
-
列坐标不变,行坐标减少(即每行从下往上遍历矩阵)
遍历完一行后,row 加一;遍历完一列后,col 加一。
其中最麻烦的应该是临界条件的控制:
-
从左往右遍历行时,列的开始下标即为保存的下标,结束下标是(总列数-(已读取列数 / 2)- 1)
-
从右往左遍历行时,列的下标范围就是 [已遍历的列数 / 2, 当前位置]
-
从上往下遍历行时,列的开始下标即为保存的下标,结束下标是(总行数-(已读取行数 / 2)- 1)
-
从下往上遍历行时,列的下标范围就是 [已遍历的行数 / 2, 当前位置]
-
遍历完的条件是 已读取的行数等于总行数或已读取的列数等于总列数 这个在每次row 和 col 变化时都要判断
结果: