剑指Offer.29——顺时针打印矩阵

题目链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

解题过程:

关键思想每遍历一行或者一列,都更新矩阵的边界

每次遍历矩阵,总有一个坐标是边界值,另一个坐标值位于两个边界值之间,所以处理好边界值即可。

遍历分从左到右,从上到下,从右到左,从下到上 这四种。

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        int row = matrix.length;
		if (row == 0)
			return new int[0];

		int col = matrix[0].length;
		int[] res = new int[row * col];
		int index = 0;
		int left = 0, right = col - 1, bottom = row - 1, top = 0;
		while (true) {
			for (int i = left; i <= right; i++) {
				res[index++] = matrix[top][i];
			}
			if (++top > bottom)
				break;

			for (int i = top; i <= bottom; i++) {
				res[index++] = matrix[i][right];
			}
			if (--right < left)
				break;

			for (int i = right; i >= left; i--) {
				res[index++] = matrix[bottom][i];
			}
			if (--bottom < top)
				break;

			for (int i = bottom; i >= top; i--) {
				res[index++] = matrix[i][left];
			}
			if (++left > right)
				break;
		}

		return res;
        
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43207025/article/details/107865259
今日推荐