码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】59.Spiral Matrix II

时间:2018-02-05 18:46:53      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:log   size   打印   visit   example   pos   tip   spi   wro   

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);
    }
}

 

【leetcode】59.Spiral Matrix II

标签:log   size   打印   visit   example   pos   tip   spi   wro   

原文地址:https://www.cnblogs.com/yumiaomiao/p/8418391.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!