How to print a given matrix in spiral form with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
 
void PrintMatrixInSpiralForm(std::vector<std::vector<int>> const &matrix) {
    if (matrix.size() == 0) {
        return;
    }
  
    int top = 0, bottom = matrix.size() - 1;
    int left = 0, right = matrix[0].size() - 1;
  
    while (1) {
        if (left > right) {
            break;
        }
         
        // top row
        for (int i = left; i <= right; i++) {
            std::cout << matrix[top][i] << " ";
        }
        std::cout << "\n";
        top++; // next row
  
        if (top > bottom) {
            break;
        }
         
        // right column
        for (int i = top; i <= bottom; i++) {
            std::cout << matrix[i][right] << " ";
        }
        std::cout << "\n";
        right--; // previous column
 
        if (left > right) {
            break;
        }
         
        // bottom row
        for (int i = right; i >= left; i--) {
            std::cout << matrix[bottom][i] << " ";
        }
        std::cout << "\n";
        bottom--; // previous row
  
        if (top > bottom) {
            break;
        }
         
        // left column
        for (int i = bottom; i >= top; i--) {
            std::cout << matrix[i][left] << " ";
        }
        std::cout << "\n";
        left++; // next column
    }
}
   
int main()
{
    std::vector<std::vector<int>> matrix = { { 1,   2,  3,  4 },
                                             { 5,   6,  7,  8 },
                                             { 9,  10, 11, 12 },
                                             { 13, 14, 15, 16 } };
   
    PrintMatrixInSpiralForm(matrix);
}
 
 
 
 
/*
run:
 
1 2 3 4 
8 12 16 
15 14 13 
9 5 
6 7 
11 
10 
 
*/

 



answered Sep 12, 2022 by avibootz
edited Sep 13, 2022 by avibootz

Related questions

1 answer 216 views
1 answer 192 views
1 answer 197 views
1 answer 218 views
1 answer 213 views
1 answer 203 views
1 answer 208 views
...