Java教程

54. Spiral Matrix

本文主要是介绍54. Spiral Matrix,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

This is an exactly same problem with "59. Spiral Matrix II". I set every direction as a status, when one direction was implemented, the current status turns to the next status.

Which different status, the scan direction is different, but all scans cannot exceed the edges of the matrix.

The time complexity is O(m*n):

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return res;
        int m = matrix.length;
        int n = matrix[0].length;
        int top = 0, bottom = m - 1, left = 0, right = n - 1;

        int status = 0;  //we set every directions as a status, there are toally 4 status.
        while (top <= bottom && left <= right) {
            if (status % 4 == 0) {  //the first direction, from left to right
                for (int j = left; j <= right; j++) {
                    res.add(matrix[top][j]);
                }
                top++;

            } else if (status % 4 == 1) {  //the second direction, from top to bottom
                for (int i = top; i <= bottom; i++) {
                    res.add(matrix[i][right]);
                }
                right--;
            } else if (status % 4 == 2) {  //the third direction, from right to left
                for (int j = right; j >= left; j--) {
                    res.add(matrix[bottom][j]);
                }
                bottom--;
            } else if (status % 4 == 3) {  //the fourth direction, from bottom to top
                for (int i = bottom; i >= top; i--) {
                    res.add(matrix[i][left]);
                }
                left++;
            }
        }
        return res;
    }

 

这篇关于54. Spiral Matrix的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!