题解 | #螺旋矩阵#

螺旋矩阵

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

import java.util.*;
public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {

        ArrayList<Integer> record=new ArrayList<Integer>();
        if(matrix==null||matrix.length==0)return record;
        int bottom=matrix.length-1;
        int right=matrix[0].length-1;
        int top=0;
        int left=0;
        while(top<=bottom&&left<=right){//只有一行或者只有一列也要进行循环啊
            for(int i=left;i<=right;i++){
                record.add(matrix[top][i]);
            }
            for(int i=top+1;i<=bottom;i++){
                record.add(matrix[i][right]);
            }
            for(int i=right-1;i>=left+1&&top<bottom;i--){//防止只有一行,从右往左重复添加
                record.add(matrix[bottom][i]);
            }
            for(int i=bottom;i>=top+1&&left<right;i--){//防止只有一列,从下网上重复添加
                record.add(matrix[i][left]);
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return record;
    }
}
全部评论

相关推荐

zhiyog:哈哈哈哈哈哈哈哈哈哈哈哈哈
点赞 评论 收藏
分享
05-13 02:01
已编辑
惠州学院 前端工程师
安静的少年在求佛:建议把公司名字写到标题。以后有人想搜就能直接搜到
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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