C++ Online Compiler
Example: Spiral Matrix Traversal in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Spiral Matrix Traversal #include <iostream> #include <vector> int main() { // Step 1: Initialize the matrix std::vector<std::vector<int>> matrix = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; int rows = matrix.size(); if (rows == 0) { std::cout << "Matrix is empty." << std::endl; return 0; } int cols = matrix[0].size(); if (cols == 0) { std::cout << "Matrix is empty." << std::endl; return 0; } // Initialize boundary pointers int top = 0; int bottom = rows - 1; int left = 0; int right = cols - 1; // Vector to store the spiral order elements std::vector<int> result; // Loop until all elements are processed while (top <= bottom && left <= right) { // Step 2: Traverse right along the top row for (int i = left; i <= right; ++i) { result.push_back(matrix[top][i]); } top++; // Move top boundary down // Step 3: Traverse down along the rightmost column for (int i = top; i <= bottom; ++i) { result.push_back(matrix[i][right]); } right--; // Move right boundary left // Step 4: Traverse left along the bottom row (if applicable) if (top <= bottom) { // Check if there's still a bottom row to process for (int i = right; i >= left; --i) { result.push_back(matrix[bottom][i]); } bottom--; // Move bottom boundary up } // Step 5: Traverse up along the leftmost column (if applicable) if (left <= right) { // Check if there's still a leftmost column to process for (int i = bottom; i >= top; --i) { result.push_back(matrix[i][left]); } left++; // Move left boundary right } } // Step 6: Print the spiral order std::cout << "Spiral order: "; for (int val : result) { std::cout << val << " "; } std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS