54. 螺旋矩阵 leetcode

先来看题:

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

输出: [1,2,3,6,9,8,7,4,5]

示例 2:

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

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

这是leetcode上一个难度偏高的题,据说也是腾讯的一个笔试题,因为在网上找不到合适的解答,所以我自己实现了一下, 做个总结,希望对大家有帮助:

思路:

首先看到这个题目,最先想到的就是用递归来实现,螺旋矩阵输出其实就是从外层到内层一圈一圈地输出,

每一圈就作为一个递归过程。

每一个递归过程分为四个步骤:

    1、从左往右

    2、从上到下

    3、从右到左

    4、从下到上

所以,我们的算法结构就是设计一个递归,递归的每一层包含以上四个输出。

java代码实现如下:

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {        
        ArrayList<Integer> resultList = new ArrayList<Integer>() ;
        if(matrix.length == 0){
            return resultList;
        }
		//nums.length 行数,nums[0].length:列数
		resultList = getEachSort(resultList, matrix, 0, matrix[0].length-1, 0, matrix.length-1); 
		return resultList;
    }
    public static ArrayList getEachSort(ArrayList<Integer> resultList, 
			int[][] nums, int beginI, int endI, int beginJ, int endJ){
		for(int j=beginI; j<=endI; j++){
			resultList.add(nums[beginJ][j]);
		}
		for(int i=beginJ+1; i<=endJ; i++){
			resultList.add(nums[i][endI]);
		}
		if(endJ>beginJ){
			for(int k=endI-1; k>=beginI; k--){
				resultList.add(nums[endJ][k]);
			}
		}
		if(beginI<endI){
			for(int p=endJ-1; p>=beginJ+1; p--){
				resultList.add(nums[p][beginI]);
			}
		}
		beginI++;
		endI--;
		beginJ++;
		endJ--;
		if(beginI<=endI && beginJ<=endJ){
			getEachSort(resultList, nums, beginI, endI, beginJ, endJ);
		}		
		return resultList;
	}
}

猜你喜欢

转载自blog.csdn.net/fhy569039351/article/details/82748179