题解 | #螺旋矩阵#

螺旋矩阵

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

import java.util.*;

public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> arr = new ArrayList<Integer>();
        if(matrix.length == 0) return arr;
        int top = 0;
        int left = 0;
        int right = matrix[0].length - 1;
        int bottom = matrix.length - 1;
        while(left <= right && top <= bottom){
            for(int col = left; col <= right; col++){
                arr.add(matrix[top][col]);
            }
            if(++top > bottom) break;
            for(int row = top; row <= bottom; row++){
                arr.add(matrix[row][right]);
            }
            if(--right < left) break;
            for(int col = right; col >= left; col--){
                arr.add(matrix[bottom][col]);
            }
            if(--bottom < top) break;

            for(int row = bottom; row >= top; row--){
                arr.add(matrix[row][left]);
            }
            if(++left > right) break;
        }
        return arr;
    }
}
全部评论

相关推荐

头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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