How to print a given matrix in the clockwise spiral form in C++
In this tutorial, we will learn how to print a given matrix in the clockwise spiral form in C++. Also, given an RxC matrix, we will print the matrix in the clockwise spiral form.
Specifically, the main idea is:
Firstly, we have to read elements from the given matrix one by one and simply, print it in the spiral order. Moreover, for spiral order, we will use four loops each for top, bottom, left, right corner of the matrix.
In other words, every loop defines a direction along with the matrix.
- The first for loop directs the movement from left to right.
- The second for loop directs the movement from top to bottom.
- The third for loop directs the movement from right to left.
- The fourth for loop directs the movement from bottom to top.
Therefore, we will use four variables here.
- a – starting row index
- b – starting column index
- c – ending row index
- d – ending column index
You may also like:
Find the sum of each row and column of a matrix in C++
Print a given matrix in the clockwise spiral form in C++
Below is the implementation of the above approach.
#include <bits/stdc++.h> #include<iostream> using namespace std; #define R 3 #define C 6 void spiralprint(int c, int d, int arr[R][C]) { int i, a = 0, b = 0; /* a - starting row index c - ending row index b - starting column index d - ending column index */ while (a < c && b < d) { /* Print the first row from the remaining*/ for (i = b; i < d; ++i) { cout << arr[a][i] << " "; } a++; /* Print the last column from the remaining columns */ for (i = a; i < c; ++i) { cout << arr[i][d - 1] << " "; } d--; /* Print the last row from the remaining rows */ if (a < c) { for (i = d- 1; i >= b; --i) { cout << arr[c - 1][i] << " "; } c--; } /* Print the first column from the remaining columns */ if (b < d) { for (i = c - 1; i >= a; --i) { cout << arr[i][b] << " "; } b++; } } } int main() { int arr[R][C] = { { 1, 2, 3, 4, 5, 6 }, { 7, 8, 9, 10, 11, 12 }, { 13, 14, 15, 16, 17, 18 } }; spiralprint(R, C, arr); return 0; }
OUTPUT EXPLANATION:
OUTPUT: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Leave a Reply