diff options
author | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
commit | 7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch) | |
tree | eb7a24ee2067f92245c57bb118e85a1baf15df50 /other/spiral_matrix.cpp | |
parent | 5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff) | |
download | leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip |
chore: move cpp and rust code to directory
Diffstat (limited to 'other/spiral_matrix.cpp')
-rw-r--r-- | other/spiral_matrix.cpp | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/other/spiral_matrix.cpp b/other/spiral_matrix.cpp new file mode 100644 index 0000000..d1c294b --- /dev/null +++ b/other/spiral_matrix.cpp @@ -0,0 +1,37 @@ +// 54. Spiral Matrix +#include "leetcode.h" + +// given an m x n 'matrix', return all elements of the 'matrix' in spiral order + +class Solution { +public: + vector<int> spiralOrder(vvd & matrix) { + vvd dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int rows = matrix.size(), cols = matrix[0].size(); + vector<int> ans, n_step{cols, rows - 1}; + if (!rows || !cols) + return ans; + int i_dir = 0, i_row = 0, i_col = -1; + while (n_step[i_dir % 2]) { + for (int i = 0; i < n_step[i_dir % 2]; ++i) { + i_row += dirs[i_dir][0]; + i_col += dirs[i_dir][1]; + ans.push_back(matrix[i_row][i_col]); + } + n_step[i_dir % 2]--; + i_dir = (i_dir + 1) % 4; + } + return ans; + } +}; + +int main() { + Solution obj; + vvd m1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + vvd m2 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; + for (auto i : obj.spiralOrder(m1)) + printf("%d, ", i); + printf("\n"); // expect: 1,2,3,6,9,8,7,4,5 + for (auto i : obj.spiralOrder(m2)) + printf("%d, ", i); // expect: 1,2,3,4,8,12,11,10,9,5,6,7 +} |