求二维数组对角钱

package com.test01;

/**
二维数组 对角线输出 两个方向
例如对于数组:
{ 1, 2, 3, 4 }, 
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }, 
{ 13, 14, 15, 16 },

slash方向输出:
1 
5 2 
9 6 3 
13 10 7 4 
14 11 8 
15 12 
16 

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

数组的行数和列数可以不相等,但同一行的元素个数必须相等,称为"矩阵"更合适
 */
public class PrintArray {

    public static void main(String[] args) {
        int[][] arr = new int[][] { 
                { 1, 2, 3, 4, }, 
                { 5, 6, 7, 8 },
                { 9, 10, 11, 12 }, 
                { 13, 14, 15, 16 }, 
        };

        slash(arr);
        System.out.println("======");
        backslash(arr);
        
        
    }
    
    public static void slash(int[][] arr) {
        if (arr == null) {
            throw new IllegalArgumentException("arr cannot be null");
        }
        int col = arr[0].length;//col列号
        int row = arr.length;//row行号
        for( int k = 0 ; k < col * 2 -1 ; k++ ) {     //k代表有多少行输出,由col决定
            int sum = k;                              //同一行的元素,行下标和列下标的和相等
            for( int j = 0 ; j < col ; j++ ) {                 
                int i = sum - j;
                if(isValidIndex(i, row) && isValidIndex(j, col)) {
                    System.out.print( arr[i][j] + " " );
                }
            }
            System.out.println();
        }
    }
    
    public static void backslash(int[][] arr) {
        if (arr == null) {
            throw new IllegalArgumentException("arr cannot be null");
        }
        int row = arr.length;
        int col = arr[0].length;
        for (int k = 0; k < col * 2 - 1; k++) {     //k代表有多少行输出,由col决定
            int diff = col - k - 1;                 //同一行的元素,行下标和列下标的差相等
            for (int j = 0; j < col; j++) {
                int i = j - diff;
                if (isValidIndex(i, row) && isValidIndex(j, col)) {
                    System.out.print(arr[i][j] + " ");
                }
            }
            System.out.println();
        }
    }

    private static boolean isValidIndex(int i, int n) {
        return i >= 0 && i < n;
    }

}


http://bylijinnan.iteye.com/blog/2056301

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值