题目要求

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].

分析

举个例子自己从头到尾把数字列出来,很容易就找到规律了:
假设一维数组的坐标为x,取值范围是xMin~xMax;二维数组的坐标为y,取值范围是yMin~yMax。(也就是数组表示为int[y][x])
1. 从左到右,y=yMin,x: xMin->xMax,yMin++
2. 从上到下,x=xMax,y: yMin->yMax,xMax--
3. 从右到左,y=yMax,x: xMax->xMin,yMax--
4. 从下到上,x=xMin,y: yMax->uMin,xMin++
结束条件,xMin==xMax或者yMin==yMax
 
还要要注意的地方:空数组的情况要处理。

Java代码

public static ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> order = new ArrayList<Integer>();
if (matrix.length == 0 || matrix[0].length == 0) return order; int xMin = 0;
int yMin = 0;
int xMax = matrix[0].length - 1;
int yMax = matrix.length - 1; order.add(matrix[0][0]); int i = 0, j = 0;
while (true) {
while (i < xMax) order.add(matrix[j][++i]);
if (++yMin > yMax) break; while (j < yMax) order.add(matrix[++j][i]);
if (xMin > --xMax) break; while (i > xMin) order.add(matrix[j][--i]);
if (yMin > --yMax) break; while (j > yMin) order.add(matrix[--j][i]);
if (++xMin > xMax) break;
}
return order;
}

最新文章

  1. Yii的学习(5)--Active Record的关联
  2. Hadoop阅读笔记(三)——深入MapReduce排序和单表连接
  3. 谈谈Delph中的类和对象2---类可以理解成一种特殊的数据结构、类型转换
  4. GTD一些问题
  5. 2016年10月18日 星期二 --出埃及记 Exodus 19:2
  6. wireshark: there are no interfaces on which a capture can be done
  7. Oracle- 备份单表结构和单表数据
  8. Django db relationship
  9. web前端面试试题总结---其他
  10. java开发第一天
  11. mysql 数据库 切表的脚本
  12. linux apache 打模块示例
  13. tablelayoutpanel内部组件变形
  14. tensorflow Sigmoid 应用
  15. 美团小程序框架mpvue入门
  16. flask请求异步执行(转载)
  17. 2018秋寒假作业4—PTA编程总结1
  18. GO流程控制
  19. git flow分支管理
  20. DXP 内电层分割

热门文章

  1. 停掉一台服务器,Nginx响应慢(转载)
  2. appium 1.6.3 + ios 10.2 + xcode 8.2.1 真机运行iphone app
  3. django abstract base class ---- 抽象基类
  4. unity, Root Motion
  5. Android批量图片载入经典系列——afinal框架实现图片的异步缓存载入
  6. iOS_5_汤姆猫
  7. Out of Hay(poj2395)(并查集)
  8. CSS3背景总结
  9. python 加密方法总结
  10. STM32F10x_硬件I2C主从通信(轮询发送,中断接收)