leetcode59.Spiral Matrix II

Posted 于淼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode59.Spiral Matrix II相关的知识,希望对你有一定的参考价值。

Leetcode59 Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,
Given n = 3, You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
回型打印整数n。

Tips:
dr dc控制指针的走向,当不满足
(newRow>=0 && newRow<n && newCol>=0 && newCol<n && !visit[newRow][newCol])这些条件时,指针就要改变方向。
package medium;

public class L59SpiralMatrixII {
    
    public int[][] generateMatrix(int n) {
        int[][] ans = new int[n][n];
        boolean[][] visit = new boolean[n][n];
        int row = 0;
        int col = 0;
        int ind = 0;
        int[] dr = { 0, 1, 0, -1 };
        int[] dc = { 1, 0, -1, 0 };
        for (int i = 0; i < n * n; i++) {
            ans[row][col] = i + 1;
            visit[row][col] = true;
            int newRow=row+dr[ind];
            int newCol=col+dc[ind];
            if(newRow>=0 && newRow<n && newCol>=0 && newCol<n && !visit[newRow][newCol]){
                row=newRow;
                col=newCol;
            }else{
                ind=(ind+1)%4;
                row+=dr[ind];
                col+=dc[ind];
            }
        }
        return ans;
    }
    public void print(int[][] ans,int n){
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                System.out.print(ans[i][j]+" ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        L59SpiralMatrixII cc= new L59SpiralMatrixII();
        int n=4;
        int[][] ans= cc.generateMatrix(n);
        cc.print(ans, n);
    }
}

 






以上是关于leetcode59.Spiral Matrix II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode59.Spiral Matrix II

[LeetCode]59. Spiral Matrix II

Leetcode59 Spiral Matrix II

[leetcode-59-Spiral Matrix II]

LeetCode59 Spiral Matrix II

LeetCode-59-Spiral Matrix II