Questions basic exercises back-shaped access
Resource constraints
Time limit: 1.0s Memory Limit: 512.0MB
Problem Description
Access is meander-shaped along the side access of the matrix, if the current direction has numerous desirable or take off, then 90 degrees left. A start left corner of the matrix, the downward direction.
Input Format
The first input line is a positive integer of not more than two of m 200, n, denotes the matrix of rows and columns. Next, each row of n row m is an integer, denotes the matrix.
Output Format
Only the output line, a total of mn number, taken as an input matrix meandering number of results obtained. Between the number separated by a space, end of the line do not have extra spaces.
Sample input
3 3
1 2 3
4 5 6
7 8 9
Sample Output
1 4 7 8 9 6 3 2 5
Sample input
3 2
1 2
3 4
5 6
Sample Output
1 3 5 6 4 2
Python version
m, n = map(int, input().split())
a = []
ans = []
for _ in range(m):
a.append(list(map(int, input().split())))
while a:
# down
for i in range(len(a)):
ans += [a[i].pop(0)] if a[i] else []
# right
ans += a.pop() if a else []
# top
for i in range(len(a) - 1, -1, -1):
ans += [a[i].pop()] if a[i] else []
# left
ans += a.pop(0)[::-1] if a else []
print(*ans)
c ++ version
#include <iostream>
#include <memory.h>
using namespace std;
int main() {
int m, n;
cin >> m >> n;
int a[201][201];
memset(a, -1, sizeof(a));
int i = 0, j = 0;
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
cin >> a[i][j];
i = 0, j = 0;
int total = 0;
while(total < m * n) {
while(i <= m-1 && a[i][j] != -1) {//down
cout << a[i][j] << " ";
a[i][j] = -1;
i++;
total++;
}
i--;
j++;
while(j <= n-1 && a[i][j] != -1) {//right
cout << a[i][j] << " ";
a[i][j] = -1;
j++;
total++;
}
j--;
i--;
while(i >= 0 && a[i][j] != -1) {//up
cout << a[i][j] << " ";
a[i][j] = -1;
i--;
total++;
}
i++;
j--;
while(j >= 0 && a[i][j] != -1) {//left
cout << a[i][j] << " ";
a[i][j] = -1;
j--;
total++;
}
j++;
i++;
}
return 0;
}