[leetcode]Spiral Matrix

简单题。但做得不简洁。里面用了一个count来计数,还是不错的。因为有可能只有一行(或子状态中),那么m_low == m_high,这时,当m_low++后,m_high大于m_low,可能会从左往右和回扫都是同一行。

public class Solution {

    public ArrayList<Integer> spiralOrder(int[][] matrix) {

        ArrayList<Integer> ans = new ArrayList<Integer>();

        int m = matrix.length;

        if (m == 0) return ans;

        int n = matrix[0].length;

        if (n == 0) return ans;

        int m_low = 0;

        int m_high = m-1;

        int n_low = 0;

        int n_high = n-1;

        int count = m*n;

        while (count > 0) {

            for (int i = n_low; i <= n_high && count > 0; i++) {

                ans.add(matrix[m_low][i]);

                count--;

            }

            m_low++;

            for (int i = m_low; i <= m_high && count > 0; i++) {

                ans.add(matrix[i][n_high]);

                count--;

            }

            n_high--;

            for (int i = n_high; i >= n_low && count > 0; i--) {

                ans.add(matrix[m_high][i]);

                count--;

            }

            m_high--;

            for (int i = m_high; i >= m_low && count > 0; i--) {

                ans.add(matrix[i][n_low]);

                count--;

            }

            n_low++;

        }

        return ans;

    }

}

  

你可能感兴趣的:(LeetCode)