leetcode:Spiral Matrix 【Java】
2016-03-06 15:02
387 查看
一、问题描述
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) { ArrayList<Integer> result = new ArrayList<Integer>(); if (matrix.length == 0) return result; int beginX = 0, endX = matrix[0].length - 1; int beginY = 0, endY = matrix.length - 1; while (true) { // From left to right for (int j = beginX; j <= endX; ++j) result.add(matrix[beginY][j]); if (++beginY > endY) break; // From top to bottom for (int i = beginY; i <= endY; ++i) result.add(matrix[i][endX]); if (beginX > --endX) break; // From right to left for (int j = endX; j >= beginX; --j) result.add(matrix[endY][j]); if (beginY > --endY) break; // From bottom to top for (int i = endY; i >= beginY; --i) result.add(matrix[i][beginX]); if (++beginX > endX) break; } return result; } }
相关文章推荐
- Java 权限修饰符
- JVM原理及优化
- Spring MVC:第二章 Spring MVC入门
- javaHDU1003Max Sum
- 容器类概述(2)—List
- 教大家看官方技术文档(三)- Spring,Mybatis整合
- 学号20145322 《Java程序设计》第一周学习总结
- 20145231 《Java程序设计》第一周学习总结
- 82——java监听者模式
- java Util
- JavaWeb Servlet
- 2016蓝桥杯假期任务之《周期字串》(90%)
- 谈谈对Spring 控制反转(IOC)及依赖注入(DI)的理解
- java导出生成word的简单方法
- java.text.SimpleDateFormat多线程下的问题
- 20145127 《Java程序设计》第一周学习总结
- 深入理解Java的接口和抽象类
- java学习笔记(7)基本概念之IO
- SpringAop
- Java文件读写操作