題目要求:
給你一個 m 行 n 列的矩陣 matrix ,請按照 順時針螺旋順序 ,返回矩陣中的所有元素。
示例 1:
輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
輸出:[1,2,3,6,9,8,7,4,5]
示例 2:
輸入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
輸出:[1,2,3,4,8,12,11,10,9,5,6,7]
代碼實現:
int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//作為方向偏移量
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize) {
//包含矩陣無元素的情況
*returnSize = 0;
return NULL;
}
//分別表示矩陣的行數和列數
//用來標記元素是否被訪問
memset(visited, 0, sizeof(visited));
int total = rows * columns;
int* order = malloc(sizeof(int) * total);
*returnSize = total;
int row = 0, column = 0;
//作為方向索引
for (int i = 0; i < total; i++) {
order[i] = matrix[row][column];
//訪問完標記該位置
int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
//控制directionIndex在0~3之間,繼續下一個循環
}
//更新行
//更新列
}
//返回最終結果
}
作者:力扣官方題解
堅持編程,我一直在路上!