转圈打印矩阵——java

[题目]:

给定一个整形矩阵,请按照转圈的方式打印它

例如矩阵:
1 2 3
4 5 6
7 8 9
转圈打印输出结果为:1 2 3 6 9 8 7 4 5

[思路]:

在矩阵中用左上角的坐标(tR,tC)和右下角的坐标(dR,dC)就可以表示一个子矩阵。例题中的矩阵,当(tR,tC)=(0,0),(dR,dC)=(2,2)时,表示的子矩阵就是整个矩阵,那么这个子矩阵最外层的部分如下:
1 2 3
4 6
7 8 9
接下来令tR和tC 加一,令dR 和dC减一,进行打印,就可以把矩阵转圈打印出来

[代码]:

import java.util.*;
public class Main{
    public static void spiralOrderPrint(int[][] m){
        int tR = 0;
        int tC = 0;
        int dR = m.length -1; //行长
        int dC = m[0].length -1; //列长
        while(tR <= dR && tC <= dC){
            printEdge(m,tR++,tC++,dR--,dC--);
        }
    }
    
    public static void printEdge(int[][]m,int tR,int tC ,int dR,int dC){
        if(tR == dR){
            //子矩阵只有一行时
            for(int i = tC; i <= dC ; i ++){
                System.out.print(m[tR][i]+" ");
            }
        }
        else if(tC == dC){
            //子矩阵只有一列时
            for(int i = tR; i <= dR ;i++ ){
                System.out.print(m[i][tC]+ " ");
            }
        }
        else{//一般情况下
            int coutC = tC;
            int coutR = tR;
            while (coutC != dC) {
                System.out.print(m[tR][coutC] + " ");
                coutC++;
            }
            while (coutR != dR) {
                System.out.print(m[coutR][dC] + " ");
                coutR++;
            }
            while (coutC != tC) {
                System.out.print(m[dR][coutC] + " ");
                coutC--;
            }
            while (coutR != tR) {
                System.out.print(m[coutR][tC] + " ");
                coutR--;
            }
        }
    }
    
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        int[][] mat = new int[m][n];
        for(int i = 0 ; i < m ; i ++){
            for(int j = 0 ; j < n ; j ++){
                mat[i][j] = sc.nextInt();
            }
        }
        spiralOrderPrint(mat);
    }
    
}

[运行结果]:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值