Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
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]amatrix to fill
[in]rnumber of rows
[in]cnumber of columns
12  {
13  int value = 1;
14  for (int i = 0; i < r; i++) {
15  for (int j = 0; j < c; j++) {
16  a[i][j] = value;
17  std::cout << a[i][j] << " ";
18  value++;
19  }
21  }
22 }
Here is the call graph for this function:

◆ main()

int main ( void  )

main function

69  {
70  int r, c;
71  std::cin >> r >> c;
72  int **a = new int *[r];
73  for (int i = 0; i < r; i++) a[i] = new int[c];
74 
75  genArray(a, r, c);
76  spiralPrint(a, r, c);
77 
78  for (int i = 0; i < r; i++) delete[] a[i];
79  delete[] a;
80  return 0;
81 }
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]amatrix to read from
[in]rnumber of rows
[in]cnumber of columns

Print start row

Print the end col

Print the end row

Print the start Col

29  {
30  int startRow = 0, endRow = r - 1;
31  int startCol = 0, endCol = c - 1;
32  int cnt = 0;
33 
34  while (startRow <= endRow && startCol <= endCol) {
35  /// Print start row
36  for (int i = startCol; i <= endCol; i++, cnt++) {
37  std::cout << a[startRow][i] << " ";
38  }
39  startRow++;
40 
41  /// Print the end col
42  for (int i = startRow; i <= endRow; i++, cnt++) {
43  std::cout << a[i][endCol] << " ";
44  }
45  endCol--;
46 
47  /// Print the end row
48  if (cnt == r * c) {
49  break;
50  }
51 
52  for (int i = endCol; i >= startCol; i--, cnt++) {
53  std::cout << a[endRow][i] << " ";
54  }
55  endRow--;
56 
57  /// Print the start Col
58  if (cnt == r * c) {
59  break;
60  }
61  for (int i = endRow; i >= startRow; i--, cnt++) {
62  std::cout << a[i][startCol] << " ";
63  }
64  startCol++;
65  }
66 }
std::cout
spiralPrint
void spiralPrint(int **a, int r, int c)
Definition: spiral_print.cpp:29
std::endl
T endl(T... args)
genArray
void genArray(int **a, int r, int c)
Definition: spiral_print.cpp:12
std::cin