leetcode_54_螺旋矩阵

在这里插入图片描述

class Solution {
       public List<Integer> spiralOrder(int[][] matrix) {
             	if(matrix==null) return  null;
    	List<Integer> res=new ArrayList<Integer>();
    	if(matrix.length==0) return  res;
    	int top=0;
    	int bottom=matrix.length-1;
    	int left=0;
    	int right=matrix[0].length-1;
    	while(left<=right && top<=bottom) {
    		
    		//top left-> top right
    		for(int i=left;i<=right;i++) {
    			res.add(matrix[top][i]);
    		}
    		top++;
    		
    		//top right-> bottom right
    		for(int i=top;i<=bottom;i++) {
    			res.add(matrix[i][right]);
    		}
    		right--;
    		
            //奇数行偶数列会导致最后多出一个数字
            if(top>bottom||left>right) break;

    		//bottom right->bottom left
    		for(int i=right;i>=left;i--) {
    			res.add(matrix[bottom][i]);
    		}
    		bottom--;
    		
    		//bottom left->top left
    		for(int i=bottom;i>=top;i--) {
    			res.add(matrix[i][left]);
    		}
    		left++;
    	}
    	return res;
    }
}

猜你喜欢

转载自blog.csdn.net/ruochen82155551/article/details/107766249