54. Spiral Matrix
来源:互联网 发布:更改mac地址 编辑:程序博客网 时间:2024/05/16 12:31
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]
.
marix [x][y++];
这里y是放在循环中自动加的
比如:
下面给出解:
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> ans = new ArrayList<Integer>(); if(matrix==null || matrix.length==0) return ans; int m = matrix.length; int n = matrix[0].length; int x=0,y=0; while(m>0 && n>0){ //only one row/column situation if(m==1){ for(int i=0;i<n;i++) ans.add(matrix[x][y++]); break; }else if(n==1){ for(int i=0;i<m;i++) ans.add(matrix[x++][y]); break; } //at the top--->right for(int i=0;i<n-1;i++) ans.add(matrix[x][y++]); //at the right---->down for(int i=0;i<m-1;i++) ans.add(matrix[x++][y]); //at the down----->left for(int i=0;i<n-1;i++) ans.add(matrix[x][y--]); //at the left---->top for(int i=0;i<m-1;i++) ans.add(matrix[x--][y]); x++; y++; m=m-2; n=n-2; } return ans; }}
m-2的原因是每次循环去头去尾的行和列
同时n-1或m-1是因为不减去的话超出bound
而x++和y++是因为使到达下一个行和列,因为循环过一次了嘛
阅读全文
0 0
- 54. Spiral Matrix && 59. Spiral Matrix II
- 59. Spiral Matrix II && 54. Spiral Matrix
- LeetCode 54. Spiral Matrix
- [LeetCode]54.Spiral Matrix
- LeetCode --- 54. Spiral Matrix
- [Leetcode] 54. Spiral Matrix
- [leetcode] 54.Spiral Matrix
- 54. Spiral Matrix
- Leetcode-54.Spiral Matrix
- **LeetCode 54. Spiral Matrix
- Leetcode 54. Spiral Matrix
- [leetcode] 54. Spiral Matrix
- 54. Spiral Matrix
- leetcode 54. Spiral Matrix
- 54. Spiral Matrix LeetCode
- 54. Spiral Matrix
- 54. Spiral Matrix
- leetcode 54. Spiral Matrix
- CentOS64安装oracle服务器
- Mac x 10.12.4 如何安装sshfs
- jsp九大内置对象---pageContext
- hdu 1251 字典树
- JavaScript面向对象和高级03
- 54. Spiral Matrix
- Linux进程通信(IPC)的方式
- centos7 克隆与注意事项
- http:101249 .jsp could not be loaded because the requested class was not found the classpath
- Kotlin初探小记:给Android Studio配置Kotlin
- STM32通过USB实现Bootloader/IAP功能
- iOS开发——解决UIScrollView控件移动错位和无法滚动
- Unity碎片整理
- 基于windows10下的tensoflow离线与在线安装