TheAlgorithms-C-Plus-Plus/Others/spiral_print.cpp

79 lines
1.5 KiB
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2017-10-08 14:22:46 +08:00
using namespace std;
2019-08-21 10:10:08 +08:00
void genArray(int a[][10], int r, int c)
{
2017-10-08 14:22:46 +08:00
2019-08-21 10:10:08 +08:00
int value = 1;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
2017-10-08 14:22:46 +08:00
a[i][j] = value;
2019-08-21 10:10:08 +08:00
cout << a[i][j] << " ";
2017-10-08 14:22:46 +08:00
value++;
}
2019-08-21 10:10:08 +08:00
cout << endl;
2017-10-08 14:22:46 +08:00
}
}
2019-08-21 10:10:08 +08:00
void spiralPrint(int a[][10], int r, int c)
{
2017-10-08 14:22:46 +08:00
2019-08-21 10:10:08 +08:00
int startRow = 0, endRow = r - 1;
int startCol = 0, endCol = c - 1;
int cnt = 0;
2017-10-08 14:22:46 +08:00
2019-08-21 10:10:08 +08:00
while (startRow <= endRow && startCol <= endCol)
{
2017-10-08 14:22:46 +08:00
///Print start row
2019-08-21 10:10:08 +08:00
for (int i = startCol; i <= endCol; i++, cnt++)
{
cout << a[startRow][i] << " ";
2017-10-08 14:22:46 +08:00
}
startRow++;
///Print the end col
2019-08-21 10:10:08 +08:00
for (int i = startRow; i <= endRow; i++, cnt++)
{
cout << a[i][endCol] << " ";
2017-10-08 14:22:46 +08:00
}
endCol--;
///Print the end row
2019-08-21 10:10:08 +08:00
if (cnt == r * c)
{
2017-10-08 14:22:46 +08:00
break;
}
2019-08-21 10:10:08 +08:00
for (int i = endCol; i >= startCol; i--, cnt++)
{
cout << a[endRow][i] << " ";
2017-10-08 14:22:46 +08:00
}
endRow--;
///Print the start Col
2019-08-21 10:10:08 +08:00
if (cnt == r * c)
{
2017-10-08 14:22:46 +08:00
break;
}
2019-08-21 10:10:08 +08:00
for (int i = endRow; i >= startRow; i--, cnt++)
{
cout << a[i][startCol] << " ";
2017-10-08 14:22:46 +08:00
}
startCol++;
}
}
int main()
{
int a[10][10];
2019-08-21 10:10:08 +08:00
int r, c;
cin >> r >> c;
genArray(a, r, c);
spiralPrint(a, r, c);
2017-10-08 14:22:46 +08:00
2019-08-21 10:10:08 +08:00
return 0;
2017-10-08 14:22:46 +08:00
}