牛客题霸NC38螺旋矩阵Java题解

牛客题霸NC38螺旋矩阵Java题解

https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31?tpId=117&&tqId=34959&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

方法:逐个遍历
解题思路:按照从左到右、从上到下、从右到左、从下到上的顺序依此遍历。

import java.util.*;
public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> list = new ArrayList<>();
 
        if(matrix.length == 0) {
            return list;
        }
 
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;
        int x = 0;
 
 
        while(true) {
            for(int i = left; i <= right; i++) {  //从左到右
               list.add(matrix[top][i]) ;
            }
 
            if(++top > bottom){
                break;
            }
            for(int i = top; i <= bottom; i++){
                 list.add( matrix[i][right]);    //从上到下
            }
 
            if(left > --right){
                break;
            }
            for(int i = right; i >= left; i--){
                  list.add(matrix[bottom][i]); //从右到左
            }
 
            if(top > --bottom){
                break;
            }
            for(int i = bottom; i >= top; i--){
                 list.add(matrix[i][left]);   //从下到上
            }
 
            if(++left > right){
               break;
            }
        }
        return list;
    }
}

 

posted @ 2020-11-27 11:36  云飞扬°  阅读(259)  评论(0编辑  收藏  举报