LeetCode刷题:54. Spiral Matrix

LeetCode刷题:54. Spiral Matrix

原题链接:https://leetcode.com/problems/spiral-matrix/

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

题目大意从给出的样例可以看出从矩阵的左上角元素开始,按照顺时针的方向顺序遍历数组元素。

算法设计

package com.bean.algorithmbasic;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SpiralMatrix {
	
	public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        if(matrix.length == 0) return res;
        
        int r_min=0, r_max = matrix.length-1, c_min =0, c_max = matrix[0].length-1;

        while(r_min <= r_max && c_min <= c_max){
          //first row
          for(int j=c_min; j <= c_max; j++)
            res.add(matrix[r_min][j]);
          r_min++;
          //last col
          for(int i=r_min; i <= r_max; i++)
            res.add(matrix[i][c_max]);
          c_max--;
          //last row
          for(int j=c_max; j >= c_min && r_min <= r_max; j--)
            res.add(matrix[r_max][j]);
          r_max--;
          //first col
          for(int i=r_max; i >= r_min && c_min <= c_max; i--)
            res.add(matrix[i][c_min]);
          c_min++;
        }
        return res;
    }

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int[][] nums=new int[][] {
			
			{1,2,3,4},
			{5,6,7,8},
			{9,10,11,12},
			{13,14,15,16}
		};
		
		List<Integer> list=spiralOrder(nums);
		Iterator<Integer> itx=list.iterator();
		while(itx.hasNext()) {
			Integer num=itx.next();
			System.out.print(num+" ");
		}
		System.out.println();
		
	}

}

输出结果:

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值