博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode------Spiral Matrix II
阅读量:7071 次
发布时间:2019-06-28

本文共 1580 字,大约阅读时间需要 5 分钟。

标题: 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 }

 

转载于:https://www.cnblogs.com/pkuYang/p/4265326.html

你可能感兴趣的文章
[Codeforces375E]Red and Black Tree
查看>>
MySQL基础学习之数据库
查看>>
python 键盘输入
查看>>
算法实验1 两个数组的中位数
查看>>
仓储管理的目标
查看>>
gcc g++ 参数介绍
查看>>
本博客供喜欢JAVA的同学一起交流学习
查看>>
trie树
查看>>
xshell常用命令大全
查看>>
秒杀?能不能先预估下服务器能不能顶的住再玩啊!!!
查看>>
Oracle回顾
查看>>
R中数据结构
查看>>
mysql数据库学习(二)--表操作
查看>>
学习Qt的一些心得笔记
查看>>
cookie与session组件
查看>>
Windows Server 2008 R2下将JBoss安装成windows系统服务
查看>>
关于dubbo服务的xml配置文件报错的问题
查看>>
Escape
查看>>
运营商 WLAN
查看>>
并发编程 —— ScheduledThreadPoolExecutor
查看>>