首页 > 其他 > 详细

59. Spiral Matrix II

时间:2018-09-17 10:56:08      阅读:200      评论:0      收藏:0      [点我收藏+]

一、题目

  1、审题

 技术分享图片

  2、分析

    给一个正整数 n,生成 nXn 的矩阵数组,其中数组值为从 1 开始的旋转增加的数值。

 

二、解答

  1、思路:

    与 54 题思路类似。

     ①、从左向右、右向左时需要判断 top 是否小与 bottom;

      ②、从上到下、下到上时需要判断 left 是否 小与 right。

    注意: 题目中说生成正矩阵,所以 ①、②的判断可以省略。

public int[][] generateMatrix(int n) {
        
        int[][] arr = new int[n][n];
        int num = 1;
        
        int left = 0;
        int right = n - 1;
        int top = 0;
        int bottom = n - 1;
        
        while(left <= right && top <= bottom) {
            
            for (int i = left; i <= right; i++) {
                arr[top][i] = num++;
            }
            top++;

            
            for (int i = top; i <= bottom; i++) {
                arr[i][right] = num++;
            }
            right--;
            
            //if(top <= bottom) {
                for (int i = right; i >= left; i--) {
                    arr[bottom][i] = num++;
                }
                bottom--;
            //}
            
            //if(left <= right) {
                for (int i = bottom; i >= top; i--) {
                    arr[i][left] = num++;
                }
                left++;
            //}
        }
   return arr;
    }
    

 

59. Spiral Matrix II

原文:https://www.cnblogs.com/skillking/p/9660790.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!