【矩阵】Spiral Matrix
来源:互联网 发布:什么样的人被借调 知乎 编辑:程序博客网 时间:2024/05/21 14:04
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]
You should return [1,2,3,6,9,8,7,4,5]
.
解法:把矩阵分成一圈一圈的单元,但需要考虑特殊情况,如只有一行或一列的情况
public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> l = new ArrayList<Integer>(); int row = matrix.length; if(row == 0) return l; int col = matrix[0].length; if(col == 0) return l; int up = 0, down = row-1, left = 0, right = col-1; while(up <= down && left<=right){ for(int i=left; i<=right; i++) l.add(matrix[up][i]); if(up == down) break;//若只有一行则已经全部打印完毕 for(int i=up+1; i<=down; i++) l.add(matrix[i][right]); if(left == right) break;//若只有一列则全部打印完毕 for(int i=right-1; i>=left; i--) l.add(matrix[down][i]); for(int i=down-1; i>up; i--) l.add(matrix[i][left]); up++; down--; left++; right--; } return l; }}
0 0
- 【矩阵】Spiral Matrix
- Spiral Matrix 螺旋矩阵
- Spiral Matrix 螺旋矩阵I
- LeetCode Spiral Matrix(螺旋矩阵)
- [LintCode] 螺旋矩阵 Spiral Matrix
- 54. Spiral Matrix 螺旋矩阵
- *[Lintcode]Spiral Matrix螺旋矩阵
- Spiral Matrix:旋转打印矩阵
- [LeetCode] Spiral Matrix 螺旋输出矩阵
- Spiral Matrix 输出旋转矩阵@LeetCode
- Spiral Matrix II 螺旋矩阵II
- Spiral Matrix II(旋转矩阵)
- LeetCode | Spiral Matrix(顺时针打印矩阵)
- [LeetCode]-Spiral Matrix I&II 螺旋矩阵
- [LeetCode] Spiral Matrix 旋转打印矩阵
- Spiral Matrix所谓的顺时针打印矩阵
- Spiral Matrix 矩阵的旋转输出
- Spiral Matrix II 矩阵的旋转输出
- wpa_supplicant的用法
- Djstra模板
- 把UE、notepad++等添加到右键菜单
- Undefined reference to 'dlsym'
- 深入Java内存模型
- 【矩阵】Spiral Matrix
- 数据结构-A*算法2
- Lua 中得for while
- SQL Server之字符串函数
- java中static作用详解
- ThinkPHP学习笔记
- 如何判断文法是LL(1)SLR(1)LR(1)LALR(1)的?
- hdu2923 Einbahnstrasse
- 删除字符串中模式串