TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
spiral_print.cpp
Go to the documentation of this file.
1
5#include <iostream>
6
12void genArray(int **a, int r, int c) {
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 }
20 std::cout << std::endl;
21 }
22}
23
29void spiralPrint(int **a, int r, int c) {
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) {
36 for (int i = startCol; i <= endCol; i++, cnt++) {
37 std::cout << a[startRow][i] << " ";
38 }
39 startRow++;
40
42 for (int i = startRow; i <= endRow; i++, cnt++) {
43 std::cout << a[i][endCol] << " ";
44 }
45 endCol--;
46
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
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}
67
69int main() {
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}
void spiralPrint(int **a, int r, int c)
void genArray(int **a, int r, int c)
int main()