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