首页 > 试题广场 >

转圈打印矩阵

[编程题]转圈打印矩阵
  • 热度指数:1556 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个整型矩阵matrix,请按照顺时针转圈的方式打印它。
示例1

输入

[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

输出

[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]

备注:
import java.util.*;
//  1 2 3
//  4 5 6
//  7 8 9
//  螺旋 1 2 3 6 9 8 7 4 5
public class Solution {
    public int[] printMatrix (int[][] matrix) {
        // 判断空
        if (matrix.length == 0 || matrix[0].length == 0) return null;
        // left   从1--2--3
        // right   从3--2--1
        // top   从1--4--7
        // bottom   从7--4--1
        int left = 0, right = matrix[0].length - 1;
        int top = 0, bottom = matrix.length - 1;
        // res[]的指针索引index
        int index = 0;
        // res[]的长度count==计算m*n
        int count = matrix.length * matrix[0].length;
        // 创建数组存放
        int[] res = new int[count];
        // 遍历
        while (top < (matrix.length+1)/2 && left < (matrix[0].length+1)/2) {
            // 1.上面1--2--3左往右
            for (int i = left; i <= right; i++) {
                res[index++] = matrix[top][i];  // 添加matrix[0][0],matrix[0][1],matrix[0][2]
            }
            // 2.右边3--6--9上往下,3(即matrix[0][2])已经添加,则top+1
            for (int i = top+1; i <= bottom; i++) {
                res[index++] = matrix[i][right];  // 添加matrix[1][2],matrix[2][2]
            }
            // 3.底面9--8--7右往左,9(即matrix[2][2])已经添加,则right-1
            // 上述条件top < (matrix.length+1)/2,以防矩阵过于大的时候重复
            for (int i = right-1; top != bottom && i >= left; i--) {
                res[index++] = matrix[bottom][i];  // 添加matrix[2][1],matrix[2][0]
            }
            // 4.左边7--4--1下往上,7(即matrix[2][0])已经添加,则bottom-1
            // 添加matrix[0][0]重复,冲突 top+1
            // 上述条件left < (matrix[0].length+1)/2,以防矩阵过于大的时候重复
            for (int i = bottom-1; left != right && i >= top+1; i--) {
                res[index++] = matrix[i][left];  // 添加matrix[1][0]
            }
            // 一圈后,top+1; bottom -1; left+1; right-1
            // 缩小范围
            top++;
            bottom--;
            left++;
            right--;
        }
        return res;
    }
}

发表于 2020-12-10 23:24:54 回复(0)
我特莫要是能有思路就不会跑到力扣上取经抄代码了,也不会告诉你们抄完了也似懂非懂的
发表于 2020-11-11 21:14:13 回复(0)

问题信息

难度:
2条回答 3485浏览

热门推荐

通过挑战的用户