顺时针方向输出n*m的矩阵(n行m列矩阵顺时针填写1~n*m)

public void Solution(int m,int n){
       int array[][]=new int[m][n];
       int count=1;
       int top=0,left=0;
       int  bottom=m-1,right=n-1;
       while (left<=right&&top<= bottom){
           //从左到右遍历上侧元素,依次为 (top,left) 到 (top,right)

           for (int column =left; column <=right ; column++) {
               array[top][column]=count++;
           }
       //从上到下遍历右侧元素,依次为 (top+1,right) 到 )(bottom,right)
           for (int row=top+1;row<= bottom;row++){
               array[row][right]=count++;
           }
           //如果 left<right 且 top<bottom,
           if (left<right&&top<bottom){
             //则从右到左遍历下侧元素(bottom,right−1) 到 (bottom,left+1)
               for (int column=right-1;column>left;column--){
                   array[ bottom][column]=count++;
               }
              // 下到上遍历左侧元素,依次为(bottom,left)到(top+1,left)
               for (int row= bottom;row>top;row--){
                   array[row][left]=count++;
               }
           }




           //遍历完当前层的元素之后,将 eft 和 top 分别增加 1,将 right 和 }bottom 分别减少 1,
           // 进入下一层继续遍历,直到遍历完所有元素为止
           left++;
           right--;
           top++;
           bottom--;



       }

       //遍历
       for (int i = 0; i <array.length; i++) {
           for (int j = 0; j <array[i].length; j++) {
               System.out.print(array[i][j]+" ");
           }
           System.out.println();
       }
   }

运行结果如下所示:
在这里插入图片描述在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值