常考数据结构与算法:螺旋矩阵m*n

题目描述

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

 

解题思路:

使用计算输出的方法,先处理上面一行,再处理右面一列,再处理下面一行,再处理左边一列,这是一个处理流程,一直这样操作,直到所有的元素都处理完成。

 

示例:

输入

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

返回值

[1,2,3,6,9,8,7,4,5]
import java.util.ArrayList;

public class SpiralOrderMe {
    public static void main(String[] args) {
            int[][] arr = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};

        SpiralOrderMe spiralOrderMe = new SpiralOrderMe();
        spiralOrderMe.spiralOrder2(arr);
    }

    /*
    * {1, 2, 3, 4},
    * {5, 6, 7, 8},
    * {9,10,11,12}
    */
    public ArrayList<Integer> spiralOrder2(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<>(50);
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return result;
        }

        // 只有一行的情况
        if (matrix.length == 1) {
            for (int i : matrix[0]) {
                result.add(i);
            }
            return result;
        }
        if (matrix[0].length == 1) {
            for (int i = 0; i < matrix.length; i++) {
                result.add(matrix[i][0]);
            }
            return result;
        }

        // 计算有多少圈
        int row = matrix.length;
        int col = matrix[0].length;
        int cycle = row < col ? row : col;
        cycle = (cycle + 1) / 2;
        int round = 0;
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int down = matrix.length - 1;
        // 总元素个数
        int total = col * row;
        int count = 0;
        while (round < cycle) {
            // 上面一行
            for (int i = left; i <= right && count < total; i++) {
                count++;
                result.add(matrix[round][i]);
            }

            top++;
            // 右边一列
            for (int i = top; i <= down && count < total; i++) {
                count++;
                result.add(matrix[i][col - round - 1]);

            }
            right--;

            // 底下一行
            for (int i = right; i >= left && count < total; i--) {
                count++;
                result.add(matrix[row - round - 1][i]);
            }
            down--;
            // 左边一列
            for (int i = down; i >= top && count < total; i--) {
                count++;
                result.add(matrix[i][round]);
            }
            left++;
            round++;
        }
        return result;
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值