题解 | #顺时针打印矩阵#

顺时针打印矩阵

http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a

题解如代码:

    public ArrayList<Integer> printMatrix(int [][] matrix) {
        int[] dx = {0,1,0,-1};
        int[] dy = {1,0,-1,0};
        int i =0,j=0;
        int rows = matrix.length;
        int cols = matrix[0].length;
        boolean[][] visited = new boolean[rows][cols];
        int max = matrix.length * matrix[0].length;
        ArrayList<Integer> list = new ArrayList<>();
        for(int k = 0,d =0;k < max;k++){
            //转向
            list.add(matrix[i][j]);
            visited[i][j] = true;
            int nextI = i + dx[d];
            int nextJ = j + dy[d];
            if(nextI<0 || nextI>=rows || nextJ<0 || nextJ>=cols || visited[nextI][nextJ]){
                d = (d+1)%4;
            }
            i = i + dx[d];
            j = j + dy[d];
        }
        return list;
    }
全部评论

相关推荐

11-19 18:44
已编辑
成都理工大学 Java
程序员花海:我面试过100+校招生,大厂后端面试不看ACM,竞赛经历含金量低于你有几份大厂实习 这个简历整体来看不错 可以海投
如何写一份好简历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务