Spiral Matrix
2015-07-24 09:59
357 查看
问题描述
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:
You should return
程序
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 List<Integer> spiralOrder(int[][] matrix) { List<Integer> path = new ArrayList<Integer>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return path; } int i = 0, j = 0; int n = matrix.length, m = matrix[0].length; int cnt = n * m; int cyc = 0; while (true) { // to right while (j < m - cyc) { path.add(matrix[i][j++]); } --j; ++i; // to bottom while (i < n - cyc) { path.add(matrix[i++][j]); } --i; --j; if (path.size() == cnt) { break; } // to left while (j >= cyc) { path.add(matrix[i][j--]); } ++j; --i; // to top while (i > cyc) { path.add(matrix[i--][j]); } ++i; ++j; if (path.size() == cnt) { break; } ++cyc; } return path; } }
相关文章推荐
- 什么是软链接,什么是硬链接。
- MYSQL---INSERT...SELECT...
- 一些基本函数实现和使用
- jQuery原型方法.pushStack源码分析
- VELT-0.1.5开发:在VS2013下进行python开发
- Callable的使用
- 南阳oj 数据结构 题目739 笨蛋难题四
- Java 动态代理机制分析及扩展,第 1 部分
- n皇后问题
- 目标检测程序开发(三)——级联分类器训练
- 决策树算法(matlab)
- linux下解压命令大全
- 【MySQL学习】MySQL PHP 语法
- leetCode(49):Count Primes
- 【SQL语句】 - Ctrl+3 查询表属性的存储过程
- leetCode(49):Count Primes 分类: leetCode 2015-07-24 09:58 117人阅读 评论(0) 收藏
- c++ 语法
- 在eclipse上以link方式安装CDT插件
- JAVA—Day01
- #1070 : RMQ问题再临