二维数组回形遍历java

题目描述

给定一个 rowrow 行 colcol 列的整数数组 array,要求从 array[0][0] 元素开始,按回形从外向内顺时针顺序遍历整个数组
输入描述

输入的第一行上有两个整数,依次为 rowrow 和 colcol。

余下有 rowrow 行,每行包含 colcol 个整数,构成一个二维整数数组。

(注:输入的 rowrow 和 colcol 保证 0 < row < 100, 0 < col < 1000<row<100,0<col<100。每个整数在int范围内。)

输出描述

按遍历顺序输出每个整数。每个整数占一行。

样例输入 1

4 4
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
样例输出 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

思路:额,这题写过好几次了,就不过多说明了。

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner read = new Scanner(System.in);
		int n = read.nextInt();
		int m = read.nextInt();
		int[][] num = new int[n][m];
		for(int i=0;i<n;i++)
			for(int j=0;j<m;j++)
			{
				num[i][j] = read.nextInt();
			}
		int up = 0;
		int down = num.length-1;
		int left = 0;
		int right = num[0].length-1;
		while(true)
		{
			for(int i=left;i<=right;i++)//往右
			{
				System.out.println(num[up][i]);
			}
			if(++up>down)
				break;
			for(int i=up;i<=down;i++)
			{
				System.out.println(num[i][right]);//xia
			}
			if(--right<left)
				break;
			for(int i=right;i>=left;i--)
			{
				System.out.println(num[down][i]);
			}
			if(--down<up)
				break;
			for(int i=down;i>=up;i--)
			{
				System.out.println(num[i][left]);
			}
			if(++left>right)
				break;
		}
		read.close();
	}

}

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值