本文主要是介绍题目 2898: 二维数组回形遍历,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述:
给定一个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++;}}}
}
这篇关于题目 2898: 二维数组回形遍历的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!