蛇行矩阵java实现

1.上三角型代码实现:

import java.util.Scanner;
//蛇行矩阵
public class SnackeMatrix {

    public static int N;
    public static int cnt;
    public static int [][] arr;
    public static void snakeMatrix(int N){
        int loop,i,j,p,q;
        arr=new int [N][N];
        //定义轮数
            for(i=0;i<N;i++){
                for(j=0,p=i,q=0;j<=i;j++){
                    arr[p][q]=++cnt;

                    if(p==0){
                        break;
                    }else{
                        p--;
                        q++;
                    }
                }
        }
    }

    public static void main(String[] args) {
        System.out.println("请输入矩阵阶数:");
        Scanner input = new Scanner(System.in);
        N=input.nextInt();
        snakeMatrix(N);
        for (int i=0;i<N;i++) {
            for (int j = 0; j <N-i; j++) {
                    System.out.print(arr[i][j] + "\t");
                   if(j==N-i-1){
                    System.out.println();
                   }
            }
        }

    }
}

输出结果:

 

2.矩阵型代码实现

//蛇行矩阵
public class SnackeMatrix {

    /**
     * @param M 矩阵行数
     * @param N 矩阵列数
     * @return 调整为蛇形矩阵后的矩阵
     */
    public static int[][] snakeMatrix(int M,int N){

       int derection=1;//初始方向设定
        int x=0,y=0,cnt=0;
        int [][] arr=new int [M][N];

        for(int i=0;i<M * N;i++){
            arr[x][y]=++cnt;
            //向上填充
            if(derection==1){
                if(x==0||y+1>=N){
                    //边沿改变方向
                    derection=0;
                    if(y+1>=N){
                        x++;//最右处则填入下一行
                    }else{
                        y++;// 非最右处则填入下一列
                    }
                }else{
                    x--;
                    y++;
                }
            }else{
                //向下填充,填充完改变方向
                if (y == 0 || x + 1 >= M) {
                    //边沿改变方向
                    derection=1;
                    if (x + 1 >= M) {
                       y++; //最底处则填入下一列
                    } else {
                        x++; //非最底处则填入下一行
                    }
                } else {
                    x++;
                    y--;
                }
            }
        }

        return arr;
    }

    public static void main(String[] args) {
        int[][] arr=snakeMatrix(5,5);
        for (int i=0;i<arr.length;i++) {
            for (int j = 0; j <arr[i].length; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
        System.out.println("ok");
    }
}

输出结果:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值