【leetcode】54.Spiral Matrix

时间:2023-03-08 19:11:22

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

For example,
Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].

Tips:Input:一个m×n的二维数组,按照顺时针打印

解决办法:每一圈递归一次。

package medium;

import java.util.ArrayList;
import java.util.List; public class L54SpiralMatrix {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null)
return null;
List<Integer> ans = new ArrayList<>();
int rows = matrix.length;
if (rows==0) return ans;
int cols = matrix[0].length;
int row = 0;
List<Integer> ans1 = spiralOrderCore(matrix, 0, rows - 1, 0, cols - 1, ans);
return ans1;
} private List<Integer> spiralOrderCore(int[][] matrix, int row, int rows, int col, int cols, List<Integer> ans) {
if (row < rows && col < cols) {
for (int c = col; c < cols; c++) {
ans.add(matrix[row][c]);
}
for (int r = row; r < rows; r++) {
ans.add(matrix[r][cols]);
}
for (int i = cols; i > col; i--) {
ans.add(matrix[rows][i]);
}
for (int i = rows; i > row; i--) {
ans.add(matrix[i][col]);
}
spiralOrderCore(matrix, row + 1, rows - 1, col + 1, cols - 1, ans);
} else if (row == rows) {
for (int c = col; c <=cols; c++) {
ans.add(matrix[row][c]);
} } else if (col == cols) {
for (int r = row; r <= rows; r++) {
ans.add(matrix[r][col]);
}
} return ans;
} public static void main(String[] args) {
System.out.println("Main start");
int[][] matrix = { { 1, 2, 3 ,4}, { 5, 6,7, 8 }, { 9,10,11,12 } ,{13,14,15,16}};
int[][] ma={{2,3}};
int[][] matrix1 = { { 1, 2, 3}, {4, 5, 6},{7, 8 , 9}};
L54SpiralMatrix l54 = new L54SpiralMatrix();
List<Integer> ans = l54.spiralOrder(ma);
System.out.println("size:"+ans.size());
for (int i = 0; i <ans.size(); i++) {
System.out.println(ans.get(i));
} }
}