Algorithms—54.Spiral Matrix

思路:写了4条读取方法。

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
    	List<Integer> list=new ArrayList<Integer>();
    	//m:行,n列
    	int mb=0;
    	int nb=0;
        int me=matrix.length;
        if (me==0) {
			return list;
		}
        int ne=matrix[0].length;
    	while (true) {
    		list=new Solution().right(matrix, mb, nb, me, ne, list);
			mb++;
			if (nb>ne-1||mb>me-1) {
				return list;
			}
			list=new Solution().low(matrix, mb, nb, me, ne, list);
			ne--;
			if (nb>ne-1||mb>me-1) {
				return list;
			}
			list=new Solution().left(matrix, mb, nb, me, ne, list);
			me--;
			if (nb>ne-1||mb>me-1) {
				return list;
			}
			list=new Solution().up(matrix, mb, nb, me, ne, list);
			nb++;
			if (nb>ne-1||mb>me-1) {
				return list;
			}
		}
    }
    public List<Integer> right(int[][] matrix,int mb,int nb,int me,int ne,List<Integer> list){
    	for (int i = nb; i < ne; i++) {
			list.add(matrix[mb][i]);
		}
    	return list;
    }
    public List<Integer> left(int[][] matrix,int mb,int nb,int me,int ne,List<Integer> list){
    	for (int i = ne-1; i >=nb; i--) {
			list.add(matrix[me-1][i]);
		}
    	return list;
    }
    public List<Integer> low(int[][] matrix,int mb,int nb,int me,int ne,List<Integer> list){
    	for (int i = mb; i < me; i++) {
			list.add(matrix[i][ne-1]);
		}
    	return list;
    }
    public List<Integer> up(int[][] matrix,int mb,int nb,int me,int ne,List<Integer> list){
    	for (int i = me-1; i >=mb; i--) {
			list.add(matrix[i][nb]);
		}
    	return list;
    }
}


耗时:272ms,中游


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值