【剑指Offer】顺时针打印矩阵

Shams ·
更新时间:2024-09-21
· 882 次阅读

顺时针打印矩阵 题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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.ArrayList; public class Solution { public ArrayList printMatrix(int [][] matrix) { ArrayList res = new ArrayList(); if(matrix == null || matrix.length == 0) { return res; } //以下四个元素为一圈的四个角,控制打印范围 int rowBegin = 0; int colBegin = 0; int rowEnd = matrix.length - 1; int colEnd = matrix[0].length - 1; while(rowBegin <= rowEnd && colBegin <= colEnd) { //从左向右遍历 for(int i = colBegin; i <= colEnd; i++) { res.add(matrix[rowBegin][i]); } //防止重复打印一圈中的四个角 rowBegin++; //从上到下 for(int i = rowBegin; i <= rowEnd; i++) { res.add(matrix[i][colEnd]); } colEnd--; //从右向左遍历,注意:需要先判断rowBegin是否满足小于rowEnd if(rowBegin = colBegin; i--) { res.add(matrix[rowEnd][i]); } rowEnd--; } //从下到上,注意:需要先判断colBegin是否满足小于colEnd if(colBegin = rowBegin; i--) { res.add(matrix[i][colBegin]); } colBegin++; } } return res; } } weixin_42956047 原创文章 120获赞 22访问量 3万+ 关注 私信 展开阅读全文
作者:weixin_42956047



offer 矩阵 剑指offer

需要 登录 后方可回复, 如果你还没有账号请 注册新账号