牛客_剑指offer题集——顺时针打印算法(java实现)

题目链接:

https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路:

想想矩阵的四周有四堵墙,每读完一层,相应的墙就加一,然后代码实现就好

需要注意的点:极端情况需要另作考虑

算法源码:

package niuke;

import java.util.ArrayList;

public class 顺时针打印矩阵 {
    public static ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> res = new ArrayList<>();

        int length_top = matrix.length;

        int width_right = matrix[0].length;
        if(length_top == 1&&width_right==1){
            res.add(matrix[0][0]);
            return res;
        }
        int top =0;
        int right = width_right-1;
        int bottom = length_top-1;
        int left = 0;
        while(left<=right&&top<=bottom){
            for(int i = left;i<=right;++i){
                res.add(matrix[top][i]);
            }
            top++;
            for(int i = top;i<=bottom;++i){
                res.add(matrix[i][right]);
            }
            right--;
            if(top<=bottom)
                for(int i = right;i>=left;--i){
                    res.add(matrix[bottom][i]);
                }
            bottom--;
            if(left<=right)
                for(int i = bottom;i>=top;--i){
                    res.add(matrix[i][left]);
                }
            left++;
        }
//        if(matrix.length%2==1){
//            res.add(matrix[(matrix.length-1)/2][(matrix.length-1)/2]);
//        }
        return res;
    }

    public static void main(String[] args) {
        int n =1;
        int[][] test = new int[5][5];
        for(int i = 0;i<5;++i){
            for(int j = 0;j<5;++j){
                test[i][j] = n++;
            }
        }
        int[][] test2 = {{1},{2},{3},{4},{5}};
        int[][] test3 = {{1,2,3,4,5},{1,2,3,4,5}};
        ArrayList<Integer> res = printMatrix(test3);
        for(Integer each:res){
            System.out.println(each);
        }
    }
}

 

代码已经ac

希望对大家有所帮助

以上

posted @ 2020-03-07 22:08  醉生梦死_0423  阅读(196)  评论(0编辑  收藏  举报