|
| 1 | +/* |
| 2 | + * Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. |
| 3 | +
|
| 4 | + * For example, |
| 5 | + * Given the following matrix: |
| 6 | +
|
| 7 | + * [ |
| 8 | + * [ 1, 2, 3 ], |
| 9 | + * [ 4, 5, 6 ], |
| 10 | + * [ 7, 8, 9 ] |
| 11 | + * ] |
| 12 | + * You should return [1,2,3,6,9,8,7,4,5]. |
| 13 | + * Created by supercoderhawk on 2017/8/16. |
| 14 | + */ |
| 15 | +#include |
| 16 | +#include |
| 17 | + |
| 18 | +int *spiralOrder(int **matrix, int matrixRowSize, int matrixColSize) { |
| 19 | + int isRow = 0; // 最内圈为行,包括一个数字 |
| 20 | + int isCol = 0; // 最内圈为列 |
| 21 | + |
| 22 | + if (matrixRowSize > matrixColSize) |
| 23 | + isCol = 1; |
| 24 | + if (matrixColSize > matrixRowSize || matrixColSize == matrixRowSize && matrixColSize % 2) |
| 25 | + isRow = 1; |
| 26 | + |
| 27 | + int *result = malloc(sizeof(int) * (matrixColSize * matrixRowSize)); |
| 28 | + int count = isRow ? matrixRowSize / 2 : matrixColSize / 2; |
| 29 | + int index = 0; |
| 30 | + for (int i = 0; i < count; ++i) { |
| 31 | + // 行 |
| 32 | + for (int col = i; col < matrixColSize - 1 - i; col++) { |
| 33 | + result[index + col - i] = matrix[i][col]; |
| 34 | + result[index + matrixRowSize + matrixColSize - 2 - 5 * i + col] = matrix[matrixRowSize - 1 - i][ |
| 35 | + matrixColSize - 1 - col]; |
| 36 | + } |
| 37 | + // 列 |
| 38 | + for (int r = i; r < matrixRowSize - 1 - i; ++r) { |
| 39 | + result[index + matrixColSize - 1 - 3 * i + r] = matrix[r][matrixColSize - 1 - i]; |
| 40 | + result[index + 2 * matrixColSize + matrixRowSize - 3 - 7 * i + r] = matrix[matrixRowSize - 1 - r][i]; |
| 41 | + } |
| 42 | + index += 2 * matrixColSize + 2 * matrixRowSize - 4 - 4 * i; |
| 43 | + } |
| 44 | + |
| 45 | + if (index == matrixColSize * matrixRowSize) |
| 46 | + return result; |
| 47 | + |
| 48 | + if (isRow) { |
| 49 | + for (int i = count; i < matrixColSize - count; ++i) { |
| 50 | + result[index++] = matrix[matrixRowSize / 2][i]; |
| 51 | + } |
| 52 | + } |
| 53 | + if (isCol) { |
| 54 | + for (int i = count; i < matrixColSize - count; ++i) { |
| 55 | + result[index++] = matrix[i][matrixColSize / 2]; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return result; |
| 60 | + |
| 61 | +} |
| 62 | + |
| 63 | +void testSpiralOrder() { |
| 64 | + int **m = malloc(sizeof(int *)), rowCount = 10, colCount = 10, *row; |
| 65 | + for (int i = 0; i < rowCount; ++i) { |
| 66 | + row = malloc(sizeof(int) * colCount); |
| 67 | + for (int j = 0; j < colCount; ++j) { |
| 68 | + row[j] = i * colCount + j + 1; |
| 69 | + } |
| 70 | + m[i] = row; |
| 71 | + } |
| 72 | + int *res = spiralOrder(m, rowCount, colCount); |
| 73 | + for (int i = 0; i < rowCount * colCount; ++i) { |
| 74 | + printf("%d,", res[i]); |
| 75 | + } |
| 76 | +} |
0 commit comments