CCF CSP201412-2Z字形扫描
思路:分奇数矩阵和偶数矩阵的情况,总共有的情况只有右移,对角移动和下移。
#include<iostream>
using namespace std;
const int maxn = 510;
int arr[maxn][maxn];
int main(){
int n;
cin>>n;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cin>>arr[i][j];
}
}
int x = 0, y = 0;
cout<<arr[x][y];
//遍历结束条件
while(x != n-1 || y != n-1){
//共有四种情况:
//1、当x==0或x==n-1, 往右移动一格 ->
if(x == 0 || x == n-1){
if(x == n-1 && y == 0 && n % 2 == 1){ //考虑到奇数矩阵此种情况不右移
}
else{
y++;
cout<<" "<<arr[x][y];
}
}
//2、向上或向下斜着走,看是否要向下转移
if(x == 0 || y == n-1){//斜下方
while(y > 0 && x < n-1){
y--;x++;
cout<<" "<<arr[x][y];
}
if(x != n-1 && y == 0){
x++;
cout<<" "<<arr[x][y];
}
}
else if(x == n-1 || y == 0){
while(y < n-1 && x > 0){
y++;x--;
cout<<" "<<arr[x][y];
}
if(x != n-1 && y == n-1){
x++;
cout<<" "<<arr[x][y];
}
}
}
return 0;
}