spiral print Algorithm
The spiral print algorithm is a technique used to traverse and print a 2D matrix in a spiral order, starting from the top-left corner and moving in a clockwise direction. This algorithm is commonly used in situations where data is arranged in a grid-like structure, such as images or spreadsheets, and we need to access the elements in a specific order. The main idea behind the algorithm is to incrementally move through the matrix, visiting each element once and printing its value, while updating the boundaries of the matrix as we progress through the spiral.
To implement the spiral print algorithm, we need to maintain four variables representing the boundaries of the current sub-matrix being traversed: top, bottom, left, and right. We start with top and left as 0, and bottom and right set to the dimensions of the matrix minus one. We then iterate through the matrix in a nested loop, printing the elements and updating the boundaries in each iteration. In the first iteration, we print the elements from the top-left to the top-right, then increment the top boundary. In the second iteration, we print the elements from the top-right to the bottom-right and increment the right boundary. In the third iteration, we print the elements from the bottom-right to the bottom-left and decrement the bottom boundary. In the fourth iteration, we print the elements from the bottom-left to the top-left and decrement the left boundary. We continue this process until all the elements in the matrix have been visited and printed.
#include <iostream>
using namespace std;
void genArray(int a[][10], int r, int c)
{
int value = 1;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
a[i][j] = value;
cout << a[i][j] << " ";
value++;
}
cout << endl;
}
}
void spiralPrint(int a[][10], int r, int c)
{
int startRow = 0, endRow = r - 1;
int startCol = 0, endCol = c - 1;
int cnt = 0;
while (startRow <= endRow && startCol <= endCol)
{
///Print start row
for (int i = startCol; i <= endCol; i++, cnt++)
{
cout << a[startRow][i] << " ";
}
startRow++;
///Print the end col
for (int i = startRow; i <= endRow; i++, cnt++)
{
cout << a[i][endCol] << " ";
}
endCol--;
///Print the end row
if (cnt == r * c)
{
break;
}
for (int i = endCol; i >= startCol; i--, cnt++)
{
cout << a[endRow][i] << " ";
}
endRow--;
///Print the start Col
if (cnt == r * c)
{
break;
}
for (int i = endRow; i >= startRow; i--, cnt++)
{
cout << a[i][startCol] << " ";
}
startCol++;
}
}
int main()
{
int a[10][10];
int r, c;
cin >> r >> c;
genArray(a, r, c);
spiralPrint(a, r, c);
return 0;
}