一道ACwing上的题,好像曾经还是某一年的北大计算机机试题目,搞透了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| # include <iostream> # include <cstdio> # include <cmath> # include <algorithm>
using namespace std;
int main(){ int n, m; int map[50][50]; cout << "请输入行数n:" << endl; cin >> n; cout << "请输入列数m:" << endl; cin >> m;
for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> map[i][j]; } }
bool status[50][50] = {false};
int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; int x = 0; int y = 0; int direction = 0;
for(int i = 0; i < n * m; i++){ int a = x; int b = y;
int next_a = a + dx[direction]; int next_b = b + dy[direction];
if( next_a >= n || next_a < 0 || next_b >= m || next_b < 0 || status[next_a][next_b] == true){ direction = (direction + 1) % 4; }
cout << map[a][b] << " " ; status[a][b] = true; x = x + dx[direction]; y = y + dy[direction];
}
cout << endl; return 0;
}
|