题目描述:
给定一个row行col列的整数数组array,要求从array[0][0]元素开始,按回形从外向内顺时针顺序遍历整个数组。如图所示:
代码:
package lanqiao;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
int array[][] = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
array[i][j] = sc.nextInt();
}
}
int p = 1;//判断遍历方式
int s = 0; //上
int x = row-1;//下
int z = 0;//左
int y = col-1;//右
for (int i = 0; i < row*col; i++) {
if (p%4==1&&z<=y){
for (int j = z; j <= y; j++) {
System.out.println(array[s][j]);
}
s++;
p++;
}else if (p%4==2&&s<=x){
for (int j = s; j <= x; j++) {
System.out.println(array[j][y]);
}
y--;
p++;
}else if (p%4==3&&y>=z){
for (int j = y; j >= z; j--) {
System.out.println(array[x][j]);
}
x--;
p++;
}else if (p%4==0&&x>=s){
for (int j = x; j >= s; j--) {
System.out.println(array[j][z]);
}
z++;
p++;
}
}
}
}