首页 > 代码库 > [leetcode] Spiral Matrix
[leetcode] Spiral Matrix
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].
https://oj.leetcode.com/problems/spiral-matrix/
思路:这题目不难理解,就是注意边界情况, 推荐用 上下左右4个bar的方法,简单不易出错。
import java.util.ArrayList;public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> res = new ArrayList<Integer>(); if (matrix == null || matrix.length < 1 || matrix[0].length < 1) return res; int left = 0; int right = matrix[0].length - 1; int top = 0; int bottom = matrix.length - 1; while (left <= right && top <= bottom) { int i; for (i = left; i <= right; i++) res.add(matrix[top][i]); for (i = top + 1; i <= bottom; i++) res.add(matrix[i][right]); if (top < bottom)//corner case, no need back to left if top==bottom for (i = right - 1; i >= left; i--) res.add(matrix[bottom][i]); if (left < right)//corner case, no need back up if left==right for (i = bottom - 1; i >= top + 1; i--) res.add(matrix[i][left]); top++; bottom--; left++; right--; } return res; } public static void main(String[] args) { int[][] matrix = new int[][] { { 1,2 }, { 5,6 }, { 9,10 } }; System.out.println(new Solution().spiralOrder(matrix)); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。