美文网首页皮皮的LeetCode刷题库
【剑指Offer】019——顺时针打印矩阵(数组)

【剑指Offer】019——顺时针打印矩阵(数组)

作者: 就问皮不皮 | 来源:发表于2019-08-18 23:01 被阅读0次

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.

解题思路

先得到矩阵的行和列数,然后依次旋转打印数据,一次旋转打印结束后,往对角分别前进和后退一个单位。
要注意单行和单列的情况。

参考代码

Java

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> printMatrix(int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        ArrayList<Integer> res = new ArrayList<>();
        if (row == 0 && col == 0) return res;

        int left = 0, right = col - 1, top = 0, bottom = row - 1;
        while (left <= right && top <= bottom) {
            // 上:从左到右
            for (int i = left; i <= right; i++) {
                res.add(matrix[top][i]);
            }
            // 右:从上到下
            for (int i = top + 1; i <= bottom; i++) {
                res.add(matrix[i][right]);
            }
            // 下:从右往左
            if (top != bottom) {
                // 防止单行情况
                for (int i = right - 1; i >= left; i--) {
                    res.add(matrix[bottom][i]);
                }
            }
            // 左:从下往上
            if (left != right) {
                for (int i = bottom - 1; i > top; i--) {
                    res.add(matrix[i][left]);
                }
            }
            left++;
            bottom--;
            top++;
            right--;
        }
        return res;
    }
}

Python

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        row, col = len(matrix),len(matrix[0])   # 矩阵行,列数
        left,right,top,bottom = 0,col - 1,0,row-1
        result = list()
        if row == 0 and col == 0:
            return result
        while left <= right and top <= bottom:
            # 上:
            for i in range(left,right + 1):
                result.append(matrix[top][i])
            # 右
            for i in range(top+1, bottom + 1):
                result.append(matrix[i][right])
            # 下
            # 判断矩阵不是一个一行的数据,否则重复
            if top !=bottom:
                for i in range(right-1,left - 1,-1):
                    result.append(matrix[bottom][i])
            # 左,同理判断不是一列的数据
            if right != left:
                for i in range(bottom - 1,top,-1):
                    result.append(matrix[i][left])
            left += 1
            right -= 1
            bottom -= 1
            top += 1
        return result

个人订阅号

image

相关文章

网友评论

    本文标题:【剑指Offer】019——顺时针打印矩阵(数组)

    本文链接:https://www.haomeiwen.com/subject/obtjsctx.html