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 rowfor(int j=c_min; j <= c_max; j++)res.add(matrix[r_min][j]);r_min++;//last colfor(int i=r_min; i <= r_max; i++)res.add(matrix[i][c_max]);c_max--;//last rowfor(int j=c_max; j >= c_min && r_min <= r_max; j--)res.add(matrix[r_max][j]);r_max--;//first colfor(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 stubint[][] 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