zoukankan      html  css  js  c++  java
  • leetcode------Spiral Matrix II

    标题: Spiral Matrix II 
    通过率: 31.3
    难度: 中等

    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 ]
    ]

    螺旋矩阵,一圈是一个循环,每次循环时都是从起点向右,向下,向左,向上,转一圈后继续下一个循环。。如上述3×3下一循环是从9开始。
    由上描述可以看出来每次循环的起点依次是(0,0)-》(1,1)-》(2,2)-》(3,3)
    每次叠加都是四个循环。直接看代码:
     1 public class Solution {
     2     public int[][] generateMatrix(int n) {
     3         int [][] result=new int[n][n];
     4         int value=1;
     5         int startx=0,starty=0,endx=n-1,endy=n-1;
     6         while(startx<=endx){
     7             value=contronl(startx,starty,endx,endy,value,result);
     8             startx++;
     9             starty++;
    10             endx--;
    11             endy--;
    12         }
    13         return result;
    14         
    15     }
    16     public int contronl(int startx,int starty,int endx,int endy,int value,int[][] result){
    17         if(startx==endx){
    18             result[startx][starty]=value;
    19             return -1;
    20         }
    21         for(int i=starty;i<=endy;i++){//向右
    22             result[startx][i]=value;
    23             value++;
    24         }
    25         for(int i=startx+1;i<=endx;i++){向下
    26             result[i][endy]=value;
    27             value++;
    28         }
    29         for(int i=endy-1;i>=starty;i--){向左
    30             result[endx][i]=value;
    31             value++;
    32         }
    33         for(int i=endx-1;i>=startx+1;i--){向上
    34             result[i][starty]=value;
    35             value++;
    36             
    37         }
    38         return value;
    39     }
    40 }
  • 相关阅读:
    x+=y与x=x+y有什么区别?
    Linux下带宽流量工具iftop实践
    使用pinyin4j实现汉字转拼音
    Spring整合Velocity模版引擎
    Json工具类库之Gson实战笔记
    腾讯移动分析 签名代码示例
    Docker搭建Portainer可视化界面
    maven 打包 spring boot 生成docker 镜像
    Mysql 为什么要选择 B+Tree
    idea 添加 注释 配置
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4265326.html
Copyright © 2011-2022 走看看