From 3221f9d06a1275ff1a3af2600cd9550146740e2b Mon Sep 17 00:00:00 2001 From: Aakrisht69 <115407142+Aakrisht69@users.noreply.github.com> Date: Thu, 20 Oct 2022 00:27:44 +0530 Subject: [PATCH] Create Spiral.cpp Hacktoberfest Submission. #13 --- Cpp/Spiral.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Cpp/Spiral.cpp diff --git a/Cpp/Spiral.cpp b/Cpp/Spiral.cpp new file mode 100644 index 0000000..3e1a352 --- /dev/null +++ b/Cpp/Spiral.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; + +vector spiralOrder(vector >& matrix) +{ + int m = matrix.size(), n = matrix[0].size(); + vector ans; + + if (m == 0) + return ans; + + vector > seen(m, vector(n, false)); + int dr[] = { 0, 1, 0, -1 }; + int dc[] = { 1, 0, -1, 0 }; + + int x = 0, y = 0, di = 0; + + // Iterate from 0 to m * n - 1 + for (int i = 0; i < m * n; i++) { + ans.push_back(matrix[x][y]); + // on normal geeksforgeeks ui page it is showing + // 'ans.push_back(matrix[x])' which gets copied as + // this only and gives error on compilation, + seen[x][y] = true; + int newX = x + dr[di]; + int newY = y + dc[di]; + + if (0 <= newX && newX < m && 0 <= newY && newY < n + && !seen[newX][newY]) { + x = newX; + y = newY; + } + else { + di = (di + 1) % 4; + x += dr[di]; + y += dc[di]; + } + } + return ans; +} + +// Driver code +int main() +{ + vector > a{ { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 }, + { 13, 14, 15, 16 } }; + + // Function call + for (int x : spiralOrder(a)) { + cout << x << " "; + } + return 0; +}