Q15 LeetCode54 螺旋矩阵

1.和上一题主体部分一模一样,加了判断语句

2. int m = matrix.length, n = matrix[0].length; 二维数组的长度

3.List得实例化

 

 

 1 class Solution {
 2     public List<Integer> spiralOrder(int[][] matrix) {
 3         
 4        List<Integer> ans=new ArrayList<>();
 5        int m = matrix.length, n = matrix[0].length;
 6        int top=0,bottom=m-1,left=0,right=n-1;
 7        while(left <= right && top <= bottom){
 8             for(int i=left;i<=right;i++){
 9                 ans.add(matrix[top][i]);
10             }
11             top++;
12             for(int i=top;i<=bottom;i++){
13                 ans.add(matrix[i][right]);
14             }
15             right--;
16             if(top <= bottom){
17             for(int i=right;i>=left;i--){
18                 ans.add(matrix[bottom][i]);
19             }
20             }
21             bottom--;
22             if(left<=right){
23             for(int i=bottom;i>=top;i--){
24                 ans.add(matrix[i][left]);
25             }
26             }
27             left++;
28        }
29        return ans;
30 
31     }
32 }

 

posted @ 2024-06-07 23:38  清川1  阅读(16)  评论(0)    收藏  举报