Java实战五 螺旋矩阵

Java实战五 螺旋矩阵,第1张

Java实战五 螺旋矩阵 脑袋清醒的时候再做题!!! 描述

给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。

数据范围:0≤n,m≤100≤n,m≤10,矩阵中任意元素都满足 ∣val∣≤100∣val∣≤100

要求:空间复杂度 O(nm)O(nm) ,时间复杂度 O(nm)O(nm)

示例1

输入:

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

返回值:

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

输入:

[]

返回值:

[]
方法一:设定边界对角线两个坐标,转圈式(题解来自牛客)

 犯太多小错误!1.for循环条件语句怎么用了“,”隔开!2.去数组重点数据时为啥在matrix(点了.)【】【】!

import java.util.*;
public class Solution {
    public ArrayList spiralOrder(int[][] matrix) {
        ArrayList res = new ArrayList<>();
        if(matrix.length == 0)
            return res;
        int x2 = matrix.length;
        int y2 = matrix[0].length;
        circle(matrix, 0, 0, x2-1, y2-1, res);
        return res;}
        void circle(int[][] matrix, int x1, int y1, int x2, int y2, List ans){
            if(x2 < x1 || y2 < y1)
                return;
            if(x1 == x2){
                for(int i = y1; i <= y2; i++)
                    ans.add(matrix[x1][i]);
                return;
            }
            if(y1 == y2){
                for(int n = x1; n<= x2; n++)
                    ans.add(matrix[n][y1]);
                    return;
            }
         // 遍历当前「圈」
        // 从左往右
           for (int i = y1; i < y2; i++) ans.add(matrix[x1][i]);
        // 从上往下
        for (int i = x1; i < x2; i++) ans.add(matrix[i][y2]);
        // 从右往左
        for (int i = y2; i > y1; i--) ans.add(matrix[x2][i]);
        // 从下往上
        for (int i = x2; i > x1; i--) ans.add(matrix[i][y1]);
 
        // 往里收一圈,继续递归遍历
        circle(matrix, x1 + 1, y1 + 1, x2 - 1, y2 - 1, ans); 
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5481619.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存