2024/9/07 LeetCode Hot100 matrix

This commit is contained in:
Cool 2024-09-07 23:57:45 +08:00
parent c0981ea681
commit 2236bdab89
1 changed files with 51 additions and 0 deletions

View File

@ -0,0 +1,51 @@
package com.cool.hot100.matrix;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/07/23:00
* DayNumber 1
* Hard 2
* Level 4
*/
public class Num54 {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list=new ArrayList<>();
if(matrix.length==0){
return list;
}
int up=0; //上界
int down=matrix.length-1; //下界
int left=0;
int right=matrix[0].length-1;
while(true){
// 向右遍历
for(int i=left;i<=right;i++){
list.add(matrix[up][i]);
}
if(++up>down)break;
// 向下遍历
for(int i=up;i<=down;i++){
list.add(matrix[i][right]);
}
if(--right<left) break;
// 向左遍历
for(int i=right;i>=left;i--){
list.add(matrix[down][i]);
}
if(--down<up)break;
// 向上遍历
for(int i=down;i>=up;i--){
list.add(matrix[i][left]);
}
if(++left>right) break;
}
return list;
}
}