spiralOrder- spiral matrix

Title

Given a matrix with m rows and n columns, please follow the clockwise spiral order to return all the elements in the matrix.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12, 11,10,9,5,6,7]

prompt:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

Problem-solving ideas

Insert picture description here
As shown in the figure, 1 and 2 are convenient to cycle according to the four modules of black, red, green and blue
. Figure 3 is a special case, as explained in the code below

Code demo

class Solution {
    public  List<Integer> spiralOrder(int[][] matrix) {
        int m=matrix.length;
        int n=matrix[0].length;
        List<Integer> list=new ArrayList<>();
        int h=0;
        int l=0;
        while (m-l>1)
        {
           //第一个黑色模块,收录
            for(int i=l;i<n-1;i++)
                list.add(matrix[h][i]);
            h++;
            m=m-1;
            //第二个红色模块收录
            for(int y=h-1;y<m;y++)
                list.add(matrix[y][n-1]);
            l++;
            n--;
            //第三个绿色模块收录
            for(int i=n;i>=l;i--)
                list.add(matrix[m][i]);
               //第四个蓝色模块收录
            for(int y=m;y>=h;y--)
            {
                list.add(matrix[y][l-1]);
                //特殊情况,跳出
                if(list.size()==matrix[0].length*matrix.length)
                    break;
            }
            if(list.size()==matrix[0].length*matrix.length)
                break;

        }
        //如图一,剩下一行没有收录,收录数据
        if(list.size()!=matrix[0].length*matrix.length)
            for(int i=l;i<=n-1;i++)
                list.add(matrix[h][i]);
        return list;
    }
}

effect

The info
answer was successful:
execution time: 0 ms, defeating 100.00% of Java users
Memory consumption: 36.6 MB, defeating 61.39% of Java users

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/114837370