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

59. Spiral Matrix II

时间:2018-09-17 11:47:23      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:分析   数值   生成   info   rate   image   inf   alt   com   

一、题目

  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

标签:分析   数值   生成   info   rate   image   inf   alt   com   

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

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