LeetCode_OJ【54】Spiral Matrix

来源:互联网 发布:ps8.0软件下载 编辑:程序博客网 时间:2024/06/02 03:39

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].


这道题思路很简单,但是有些边边角角要注意,特别要注意m>n和m<n时里层的循环。

public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {List<Integer> list = new ArrayList<Integer>();if(matrix.length == 0)    return list;        for(int i = 0 ; i < (matrix.length+1) /2 && i < (matrix[0].length+1)/2 ; i++){        int flagX = 0;        int flagY = 0;        for(int j = i,count =0 ; j < matrix[i].length - i ; j ++){        list.add(matrix[i][j]);        count ++;        if(count ==2)        flagX = 1;        }        for(int j = i +1 ; j < matrix.length - i ; j ++){        list.add(matrix[j][matrix[i].length -1 -i]);        flagY = 1;        }        if(flagY > 0){        for(int j = matrix[i].length -i -2; j >= i ; j --)        list.add(matrix[matrix.length -1 -i][j]);        }        if(flagX > 0){        for(int j = matrix.length -2 -i; j > i ; j--)        list.add(matrix[j][i]);        }        }        return list;    }}


0 0
原创粉丝点击