顺时针打印矩阵(Python and C++解法)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了顺时针打印矩阵(Python and C++解法),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2473字,纯文字阅读大概需要4分钟。
内容图文
![顺时针打印矩阵(Python and C++解法)](/upload/InfoBanner/zyjiaocheng/1198/0f3dccab02b247cdbf9564bc2e75f6d3.jpg)
题目:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入: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]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
思路:
A00 A01 A02 A03
D10 E11 E12 B13
D20 G21 F22 B23
C30 C31 C32 B33
第一圈的起点(0,0),第二圈的起点(1,1)...
打印循环终止条件:对于一个n*m矩阵,存在2*star < n and 2*start <m
每一行每一列的打印前提条件见C++注释。
C++解法:
1 class Solution { 2 public : 3 vector<int> spiralOrder(vector<vector<int>>& matrix) { 4if (matrix.size() == 0) return {}; // 返回空的方法 5int rows = matrix.size(), columns = matrix[0].size(); 6 vector<int> orderResult; // 存储结果 7int start = 0; // 起点 8 9while (rows > 2 * start && columns > 2 * start) { // 打印终止的条件10int endX = columns - 1 - start; // 终止行号11int endY = rows - 1 - start; // 终止列号 1213// 从左到右打印,这一步总会有 14for (int i = start; i <= endX; i++) 15 orderResult.push_back(matrix[start][i]); 16// 判断是否需要从上到下打印,终止行号需要大于起始行号17if (start < endY) 18for (int i = start + 1; i <= endY; i++) // 从上到下打印19 orderResult.push_back(matrix[i][endX]); 20// 判断是否需要从右到左打印,终止行/列号都需要大于起始行/列号,即至少两行两列21if (start < endX && start < endY) 22for (int i = endX - 1; i >= start; i--) 23 orderResult.push_back(matrix[endY][i]); 24// 判断是否需要从下到上打印,不仅终止列号需要大于起始列号,终止行号也要比起始行号大2,即至少三行两列25if (start < endX && start < endY - 1) 26for (int i = endY - 1; i >= start + 1; i--) 27 orderResult.push_back(matrix[i][start]); 2829 start += 1; 30 } 31return orderResult; 32 } 33 };
Python解法:
1 class Solution: 2 def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 3if len(matrix) == 0: 4return [] 5 rows = len(matrix) 6 colums = len(matrix[0]) 7 start = 0 8 orderResult = [] 910while rows > 2 * start and colums > 2 * start: 11 endX = colums - 1 - start 12 endY = rows - 1 - start 1314for i in range(start, endX+1): # 从左到右打印15 orderResult.append(matrix[start][i]) 1617if endY > start: # 从上到下打印18for i in range(start + 1, endY+1): 19 orderResult.append(matrix[i][endX]) 2021if endX > start and endY > start: # 从右到左打印22for i in range(endX - 1, start - 1, -1): 23 orderResult.append(matrix[endY][i]) 2425if endX > start and endY - 1 > start: # 从下到上打印26for i in range(endY - 1, start, -1): 27 orderResult.append(matrix[i][start]) 2829 start += 1 30return orderResult
原文:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13264031.html
内容总结
以上是互联网集市为您收集整理的顺时针打印矩阵(Python and C++解法)全部内容,希望文章能够帮你解决顺时针打印矩阵(Python and C++解法)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。