Leetcode: Spiral Matrix
来源:互联网 发布:单页面淘宝客 编辑:程序博客网 时间:2024/06/08 11:03
Problem:
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]
.
Solution:
Main Idea: use for indicator to indicate the current traversal start, end of the row and column.
Code:
public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> result = new ArrayList<Integer>(); if (matrix == null || matrix.length == 0) return result; int a = 0; int b = matrix.length - 1; int c = 0; int d = matrix[0].length - 1; while (a <= b && c <= d) { if (a <= b && c <= d) { for (int j = c; j <= d; j++) { result.add(matrix[a][j]); } a++; } if (a <= b && c <= d) { for (int i = a; i <= b; i++) { result.add(matrix[i][d]); } d--; } if (a <= b && c <= d) { for (int j = d; j >= c; j--) { result.add(matrix[b][j]); } b--; } if (a <= b && c <= d) { for (int i = b; i >= a; i--) { result.add(matrix[i][c]); } c++; } } return result; }}
0 0
- [leetcode]Spiral Matrix&&Spiral Matrix II
- Leetcode:Spiral Matrix与Spiral Matrix II
- LeetCode | Spiral Matrix /Spiral Matrix II
- 【Leetcode】【python】Spiral Matrix/Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix
- [Leetcode] Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode] Spiral Matrix
- leetcode 80: Spiral Matrix
- [Leetcode] Spiral Matrix
- [LeetCode]Spiral Matrix
- [LeetCode]Spiral Matrix II
- 详解C# 迭代器
- Coroutines in Unity3d (C# version)----在unity3D中的协同(基于C#)
- C#之旅(二): IEnumerable IEnumerator
- Go 语言解面试题1
- hdoj1251统计问题
- Leetcode: Spiral Matrix
- 移动端开发心得(2015.3.1更新)
- poj 3469 Dual Core CPU(最小割)
- Ubuntu下搭建tftp服务器最简单方法 (整理转载)
- Symmetric Tree - Leetcode
- Pass-by-reference in C++ and java
- 浙大机试2008:魔咒词典
- Same Tree - Leetcode
- 老生常谈——哈希表