C++ Program to Traverse Matrix Helically
Write C++ Program to Traverse Matrix Helically
// CPP Program to Traverse Matrix Helically
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int A[3][3] = {{1, 2, 0}, {4, 0, 6}, {7, 8, 0} };
int top, bottom, left, right, dir, i, j;
int row = sizeof(A) / sizeof(A[0]);
int column = sizeof(A[0]) / sizeof(A[0][0]);
cout << "Matrix A :--> \n";
for(i = 0;i < 3; i++)
{
for( j = 0; j < 3; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
top = 0;
bottom = row - 1;
left = 0;
right = column - 1;
dir = 0;
cout << "\n\nPrinting Matrix Helically :--> ";
while(top <= bottom && left <= right)
{
if(dir == 0) //for moving right
{
for(i = left;i <= right;i++)
cout << A[top][i] << " ";
top++;
}
else if(dir == 1) //for moving down
{
for(i = top;i <= bottom; i++)
cout << A[i][right] << " ";
right--;
}
else if(dir == 2) //for moving left
{
for(i = right;i >= left; i--)
cout << A[bottom][i] << " ";
bottom--;
}
else if(dir == 3) //for moving up
{
for(i = bottom;i >= top; i--)
cout << A[i][left] << " ";
left++;
}
dir = (dir + 1 ) % 4;
cout << " ";
}
return 0;
}
Output:
Matrix A :-->
1 2 0
4 0 6
7 8 0
Printing Matrix Helically :--> 1 2 0 6 0 8 7 4 0