54Spiral Matrix

来源:互联网 发布:it安全管理 编辑:程序博客网 时间:2024/06/02 05:27

题目链接:https://leetcode.com/problems/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].

解题思路:
1、先确定二维数组包含几个圈
2、每一圈用四个 while 循环遍历(从左到右,从上到下,从右到左,从下到上 的)元素
3、第一个 while 循环是必须的;第三个 while 循环只有经过第二个 while 循环后才会执行,也就是说二维数组的行数必须大于 1 时,才会执行从右到左的扫描;第四个 while 循环必须经过第二和第三个 while 循环后才执行,即数组的行数列数都必须大于 2 才执行从下到上的扫描。
注:《剑指Offer》上有类似的题目!!

public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        List<Integer> list = new ArrayList();        if(matrix == null || matrix.length == 0 || matrix[0].length == 0)            return list;        int row = matrix.length;        int columns = matrix[0].length;        if(row == 1 && columns == 1) {            list.add(matrix[0][0]);            return list;        }        int n = Math.min(row, columns);        int circleNum;        if(n % 2 == 0)            circleNum = n / 2;        else            circleNum = n / 2 + 1;        for(int k = 0 ; k < circleNum; k ++) {            int i = k;            int j = k;            while(j < (columns - k)) {                list.add(matrix[i][j]);                j ++;            }            j --;            i ++;            while(i < row - k) {                list.add(matrix[i][j]);                i ++;            }            if(i != row - k)                break;            i --;            j --;            while(j >= k && i != k) {                list.add(matrix[i][j]);                j --;            }            if(j != k - 1)                break;             j ++;            i --;            while(i >= k + 1 && columns != 1) {                list.add(matrix[i][j]);                i --;            }        }        return list;    }}
21 / 21 test cases passed.Status: AcceptedRuntime: 276 ms

方法相似的题目:59 Spiral Matrix II

0 0