顺时针打印矩阵

顺时针打印矩阵,首先要确定循环终止的条件,就是top=bottom, left=right
先从左到右打印第一行,再从上到下打印最后一列,接着从右到左打印最后一行,最后从下到上打印第一列。执行完一次循环之后,top++;right–;bottom–;left++。进行判断left和right,top和bottom,如果不相等继续循环打印。

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        if(row == 0 || col == 0)
            return null;
        ArrayList<Integer> list = new ArrayList<Integer>();
        int left = 0, top = 0, bottom = row-1, right = col-1;
        while(top<=bottom && left<=right){
            for(int i=left;i<=right;i++){
                list.add(matrix[top][i]);
            }
            for(int j=top+1;j<=bottom;j++){
                list.add(matrix[j][right]);
            }
            if(top != bottom){
                for(int t=right-1;t>=left;t--){
                    list.add(matrix[bottom][t]);
                }
            }
            if(left != right){
                for(int k=bottom-1;k>top;k--){
                    list.add(matrix[k][left]);
                }
               }
          top++;left++;right--;bottom--;
        }
        return list;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值