document spiral print

This commit is contained in:
Krishna Vedala 2020-05-28 15:27:49 -04:00
parent 2216628678
commit 51affd4aa4
No known key found for this signature in database
GPG Key ID: BA19ACF8FC8792F7

View File

@ -1,78 +1,81 @@
/**
* @file
* @brief Print the elements of a matrix traversing it spirally
*/
#include <iostream> #include <iostream>
using namespace std;
void genArray(int a[][10], int r, int c)
{
/** Arrange sequence of numbers from '1' in a matrix form
* \param [out] a matrix to fill
* \param [in] r number of rows
* \param [in] c number of columns
*/
void genArray(int **a, int r, int c) {
int value = 1; int value = 1;
for (int i = 0; i < r; i++) for (int i = 0; i < r; i++) {
{ for (int j = 0; j < c; j++) {
for (int j = 0; j < c; j++)
{
a[i][j] = value; a[i][j] = value;
cout << a[i][j] << " "; std::cout << a[i][j] << " ";
value++; value++;
} }
cout << endl; std::cout << std::endl;
} }
} }
void spiralPrint(int a[][10], int r, int c)
{
/** Traverse the matrix spirally and print the sequence of elements
* \param [in] a matrix to read from
* \param [in] r number of rows
* \param [in] c number of columns
*/
void spiralPrint(int **a, int r, int c) {
int startRow = 0, endRow = r - 1; int startRow = 0, endRow = r - 1;
int startCol = 0, endCol = c - 1; int startCol = 0, endCol = c - 1;
int cnt = 0; int cnt = 0;
while (startRow <= endRow && startCol <= endCol) while (startRow <= endRow && startCol <= endCol) {
{ /// Print start row
for (int i = startCol; i <= endCol; i++, cnt++) {
///Print start row std::cout << a[startRow][i] << " ";
for (int i = startCol; i <= endCol; i++, cnt++)
{
cout << a[startRow][i] << " ";
} }
startRow++; startRow++;
///Print the end col /// Print the end col
for (int i = startRow; i <= endRow; i++, cnt++) for (int i = startRow; i <= endRow; i++, cnt++) {
{ std::cout << a[i][endCol] << " ";
cout << a[i][endCol] << " ";
} }
endCol--; endCol--;
///Print the end row /// Print the end row
if (cnt == r * c) if (cnt == r * c) {
{
break; break;
} }
for (int i = endCol; i >= startCol; i--, cnt++) for (int i = endCol; i >= startCol; i--, cnt++) {
{ std::cout << a[endRow][i] << " ";
cout << a[endRow][i] << " ";
} }
endRow--; endRow--;
///Print the start Col /// Print the start Col
if (cnt == r * c) if (cnt == r * c) {
{
break; break;
} }
for (int i = endRow; i >= startRow; i--, cnt++) for (int i = endRow; i >= startRow; i--, cnt++) {
{ std::cout << a[i][startCol] << " ";
cout << a[i][startCol] << " ";
} }
startCol++; startCol++;
} }
} }
int main() /** main function */
{ int main() {
int a[10][10];
int r, c; int r, c;
cin >> r >> c; std::cin >> r >> c;
int **a = new int *[r];
for (int i = 0; i < r; i++) a[i] = new int[c];
genArray(a, r, c); genArray(a, r, c);
spiralPrint(a, r, c); spiralPrint(a, r, c);
for (int i = 0; i < r; i++) delete[] a[i];
delete[] a;
return 0; return 0;
} }