Spiral matrix (traverse the matrix clockwise)

leetcode 54. Spiral matrix 

Given a   matrix of m rows and columns   , please   return all elements in the matrix in clockwise spiral order .nmatrix

Similar to the sword-pointing office 29 question;

Idea: Since we are traversing a circle clockwise, we will traverse from the top, right, bottom, and left respectively. After one circle is completed, we will traverse the next circle until the termination condition is met and the loop will stop. During the process, we will traverse the value Store it in the collection and return it to the collection;

The general idea is as shown above, which is very simple, but the difficulty of this question is:

1. Ensure that the value of the boundary is correct and there will be no array out-of-bounds

2. We need to keep the left closing, right opening or left opening and right closing uniform during each traversal.

3. Judgment of termination conditions, when is all traversal completed?

First of all, we need to define four variables, namely top, right, bottom and left. They respectively represent the positions of the top, right, bottom and left sides of the current circle being traversed. Each time it is traversed, the corresponding position will be reduced (here you can To achieve left opening and right closing or left closing and right opening), until we meet left and right, or up and down, this means that each number has been traversed, which is the termination condition.

To sum up, the code is as follows:

public List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> lists = new ArrayList<>();
    int m = matrix.length ;//定义行数
    int n = matrix[0].length ;//定义列数
    //上下左右
    //注意,这里的上下左右四个值,分别指的是遍历这一行或者这一列时,保持不动的那个行数或列数
    //例如我们遍历第一行时,行数是up保持不变,列数是i进行递增
    int up = 0;//遍历时的点坐标[up,i]
    int right = n-1;//[i,right]
    int down = m-1;//[down,i]
    int left = 0;//[i,left]

    while (true){
        //从左到右
        for (int i = left; i <= right; i++) {lists.add(matrix[up][i]);}
        if (++up>down){break;}//每一行或者一列遍历完后,都要缩圈,这里是上边向下缩圈
        //up已经完成加1操作,向下移动了一行,因为下面的从上到下遍历,是从up这一行开始的
        //所以就实现了我们的右闭,后面的以此类推;
        //当移动后的up与down冲突时,意味着遍历已经结束了,break跳出循环,下面的同理。

        //从上到下
        for (int i = up; i <= down; i++) {lists.add(matrix[i][right]);}
        if (--right<left){break;}//右边遍历完,向左缩圈

        //从右到左
        for (int i = right; i >= left; i--) {lists.add(matrix[down][i]);}
        if (--down<up){break;}//下边遍历完,向上缩圈

        //从下到上
        for (int i = down; i >= up; i--) {lists.add(matrix[i][left]);}
        if (++left>right){break;}//左边遍历完,向右缩圈
    }
    return lists;
}

Guess you like

Origin blog.csdn.net/weixin_52394141/article/details/131310335