题解 | #螺旋矩阵#

螺旋矩阵

http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31

import java.util.*;
public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> array = new ArrayList<>();
        if(matrix.length==0)          //要在获取矩阵属性前判断是否为空
            return array;
        int row = matrix.length;//行数
        int col = matrix[0].length;//列数
        int top = 0, bottom = row-1;
        int left = 0,right = col - 1;
      //当行和列为技术时,要让从上向下和从左向右的多加一
        while(top<(row+1)/2&&left<(col+1)/2){
            for(int i=left;i<=right;i++){
                array.add(matrix[top][i]);
            }
            for(int i=top+1;i<=bottom;i++){
                array.add(matrix[i][right]);
            }
          //从下向上找时,要避免bottom与top相同
            for(int i=right-1;top!=bottom && i>=left;i--){
                array.add(matrix[bottom][i]);
            }
          //从右向左找时,要避免left与right相同
            for(int i=bottom-1;left!=right&&i>=top+1;i--){
                array.add(matrix[i][left]);
            }
            top++;
            left++;
            right--;
            bottom--;
        }
        return array;
    }
}
全部评论

相关推荐

06-07 19:59
门头沟学院 C++
补药卡我啊😭:都快15年前的了还在11新特性
你的简历改到第几版了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务