spiral_print.cpp File Reference

Print the elements of a matrix traversing it spirally. More...

`#include <iostream>`
Include dependency graph for spiral_print.cpp:

## Functions

void | genArray (int **a, int r, int c)
void | spiralPrint (int **a, int r, int c)
int | main ()

## Detailed Description

Print the elements of a matrix traversing it spirally.

## Function Documentation

## genArray()

void genArray | ( | int ** | a,
|  | int | r,
|  | int | c
| ) |  |

Arrange sequence of numbers from '1' in a matrix form

Parameters

  [out] | a | matrix to fill
  [in] | r | number of rows
  [in] | c | number of columns

{
int value = 1;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
a[i][j] = value;
std::cout << a[i][j] << " ";
value++;
}
std::cout << std::endl;
}
}
std::cout
std::endl
T endl(T... args)
Here is the call graph for this function:

## main()

int main | ( | void |  | ) |

main function

{
int 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);
spiralPrint(a, r, c);
for (int i = 0; i < r; i++) delete[] a[i];
delete[] a;
return 0;
}
std::cin
spiralPrint
void spiralPrint(int **a, int r, int c)
Definition: spiral_print.cpp:29
genArray
void genArray(int **a, int r, int c)
Definition: spiral_print.cpp:12
Here is the call graph for this function:

## spiralPrint()

void spiralPrint | ( | int ** | a,
|  | int | r,
|  | int | c
| ) |  |

Traverse the matrix spirally and print the sequence of elements

Parameters

  [in] | a | matrix to read from
  [in] | r | number of rows
  [in] | c | number of columns

Print start row

Print the end col

Print the end row

Print the start Col

{
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++) {
std::cout << a[startRow][i] << " ";
}
startRow++;
/// Print the end col
for (int i = startRow; i <= endRow; i++, cnt++) {
std::cout << a[i][endCol] << " ";
}
endCol--;
/// Print the end row
if (cnt == r * c) {
break;
}
for (int i = endCol; i >= startCol; i--, cnt++) {
std::cout << a[endRow][i] << " ";
}
endRow--;
/// Print the start Col
if (cnt == r * c) {
break;
}
for (int i = endRow; i >= startRow; i--, cnt++) {
std::cout << a[i][startCol] << " ";
}
startCol++;
}
}