Java教程

59. Spiral Matrix II

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

This is the same problem with https://www.cnblogs.com/feiflytech/p/15862380.html

    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int top = 0, bottom = n - 1, left = 0, right = n - 1;
        int num = 1;
        int status = 0;
        while (top <= bottom && left <= right) {
            if (status % 4 == 0) {
                for (int j = left; j <= right; j++) {
                    matrix[top][j] = num++;
                }
                top++;
            } else if (status % 4 == 1) {
                for (int i = top; i <= bottom; i++) {
                    matrix[i][right] = num++;
                }
                right--;
            } else if (status % 4 == 2) {
                for (int j = right; j >= left; j--) {
                    matrix[bottom][j] = num++;
                }
                bottom--;
            } else if (status % 4 == 3) {

                for (int i = bottom; i >= top; i--) {
                    matrix[i][left] = num++;
                }
                left++;
            }
            status++;
        }
        return matrix;
    }

 

这篇关于59. Spiral Matrix II的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!