螺旋矩阵

2021/10/12 23:18:09

本文主要是介绍螺旋矩阵,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

链接
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素

import java.util.*;


public class Solution {
    public int[] SpiralMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }
        int n = matrix.length, m = matrix[0].length;
        int[] ret = new int[n * m];

        int row1 = 0, col1 = 0, row2 = n - 1, col2 = m - 1;

        int index = 0;
        while (row1 <= row2 && col1 <= col2) {
            if (row1 == row2) {
                for (int i = col1; i <= col2; ++i) {
                    ret[index++] = matrix[row1][i];
                }
            } else if (col1 == col2) {
                for (int i = row1; i <= row2; ++i) {
                    ret[index++] = matrix[i][col1];
                }
            } else {
                for (int i = col1; i < col2; ++i) {
                    ret[index++] = matrix[row1][i];
                }

                for (int i = row1; i < row2; ++i) {
                    ret[index++] = matrix[i][col2];
                }

                for (int i = col2; i > col1; --i) {
                    ret[index++] = matrix[row2][i];
                }

                for (int i = row2; i > row1; --i) {
                    ret[index++] = matrix[i][col1];
                }

            }

            row1++;
            col1++;
            row2--;
            col2--;
        }

        return ret;
    }
}


这篇关于螺旋矩阵的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程