From 993f5ffa7041a6bda1b72e4fd369dd5745ffb61d Mon Sep 17 00:00:00 2001 From: Ujjansh Sundram Date: Fri, 3 Oct 2025 13:07:13 +0530 Subject: [PATCH] Solved the question of spiral matrix traversal (leetcode) --- leetcode/54.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 leetcode/54.c diff --git a/leetcode/54.c b/leetcode/54.c new file mode 100644 index 0000000000..6d37cca95e --- /dev/null +++ b/leetcode/54.c @@ -0,0 +1,55 @@ + +#include +#include + +// Function to return spiral order of matrix +int* spiralOrder(int** matrix, int n, int m, int* returnSize) +{ + // Allocate space for result + int* ans = (int*)malloc(n * m * sizeof(int)); + *returnSize = 0; // keeps track of how many elements are stored + + // Define boundaries + int top = 0, bottom = n - 1; + int left = 0, right = m - 1; + int traversedCount = 0; + int total = n * m; + + // Traverse while we haven't covered all elements + while (traversedCount < total) + { + // Traverse from left to right (top row) + for (int j = left; j <= right && traversedCount < total; j++) + { + ans[(*returnSize)++] = matrix[top][j]; + traversedCount++; + } + top++; + + // Traverse from top to bottom (right column) + for (int i = top; i <= bottom && traversedCount < total; i++) + { + ans[(*returnSize)++] = matrix[i][right]; + traversedCount++; + } + right--; + + // Traverse from right to left (bottom row) + for (int j = right; j >= left && traversedCount < total; j--) + { + ans[(*returnSize)++] = matrix[bottom][j]; + traversedCount++; + } + bottom--; + + // Traverse from bottom to top (left column) + for (int i = bottom; i >= top && traversedCount < total; i--) + { + ans[(*returnSize)++] = matrix[i][left]; + traversedCount++; + } + left++; + } + + return ans; +}