diff options
Diffstat (limited to 'Computer_Science/leetcode/#54-spiral_matrix.c#')
| -rw-r--r-- | Computer_Science/leetcode/#54-spiral_matrix.c# | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/Computer_Science/leetcode/#54-spiral_matrix.c# b/Computer_Science/leetcode/#54-spiral_matrix.c# new file mode 100644 index 0000000..244cfd1 --- /dev/null +++ b/Computer_Science/leetcode/#54-spiral_matrix.c# @@ -0,0 +1,36 @@ +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ + +#define MIN(a, b) ((a) > (b) ? (b) : (a)) +int* spiralOrder(int** matrix, int matrixRowSize, int matrixColSize) { + int* result = malloc(matrixRowSize * matrixColSize); + int index = 0; + int offset; + int maxOffset = MIN(matrixRowSize, matrixColSize) / 2 + 1; + + for(offset = 0; offset < maxOffset; offset++, matrixColSize--, matrixRowSize--) { + if(matrixRowSize == 0 || matrixColSize == 0) + break; + else if(matrixRowSize == 1) { + for(int i = 0; i < matrixColSize; i++) + result[index++] = matrix[offset][offset + i]; + break; + } else if(matrixColSize == 1) { + for(int i = 0; i < matrixRowSize; i++) + result[index++] = matrix[offset + i][offset]; + break; + } else { + for(int i = 0; i < matrixColSize; i++) + result[index++] = matrix[offset][offset + i]; + for(int i = 1; i < matrixRowSize; i++) + result[index++] = matrix[offset + i][offset + matrixColSize - 1]; + for(int i = 1; i < matrixColSize; i++) + result[index++] = matrix[offset + matrixRowSize - 1][offset + matrixColSize - 1 - i]; + for(int i = 1; i < matrixRowSize - 1; i++) + result[index++] = matrix[offset + matrixRowSize - 1 - i][offset]; + } + } + + return result; +} |
