输入一个n行m列的矩阵,从左上角开始将其按回字形的顺序顺时针打印出来
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, m;
int arr[50][50];
cin >> n >> m;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
cin >> arr[i][j];
bool st[50][50] = {false};//这里是为了判断是否走过这个地方
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};//想象一个游戏机,这里就是为了输出方向控制上下左右的
int d = 1, x = 0, y = 0;
for (int i = 0; i < n * m; i ++ )
{
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= m || st[a][b])
{
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
cout << arr[x][y] << ' ';
st[x][y] = true;
x = a, y = b;
}
cout << endl;
return 0;
}
作者:yxc
链接:https://www.acwing.com/file_system/file/content/whole/index/content/3589284/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。