博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] Spiral Matrix | 把一个2D matrix用螺旋方式打印
阅读量:4513 次
发布时间:2019-06-08

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

Java 版本代码如下:

public int[][] generateMatrix(int n) {        int[][] res = new int[n][n];        int value = 1;        int left = 0, right = n-1, top = 0, bottom = n-1;        while(top < bottom && left < right)        {            //corresponding to the red part            for(int j = left; j < right; j++)            {                res[top][j] = value++;            }            //corresponding to the blue part            for(int i = top; i < bottom; i++)            {                res[i][right] = value++;            }            //corresponding to the yellow part            for(int j = right; j > left; j--)            {                res[bottom][j] = value++;            }            //corresponding to the purple part            for(int i = bottom; i > top; i--)            {                res[i][left] = value++;            }            top++;            bottom--;            left++;            right--;        }        if(n%2!=0) res[n/2][n/2]=value;        return res;    }

 

思路,定义四个变量 top, bottom, left, right分别bound住四边。然后可以按照下图的方法填充res矩阵。填充顺序是(1) 红色,(2) 蓝色,(3) 绿色,(4) 紫色。

把最外面填充完全后。开始top++, bottom--, left++, right--来把四个边往里面移。

* 如果n是奇数,最后中间那个值要单独处理, res[n/2][n/2] = k.

 

原题: 

转载至:

转载于:https://www.cnblogs.com/cblin/p/6552134.html

你可能感兴趣的文章
234 Palindrome Linked List
查看>>
Keil-MDK编译完成后代码大小
查看>>
ArcGIS JS 学习笔记4 实现地图联动
查看>>
ubuntu 12.04 lts安装golang并设置vim语法高亮
查看>>
编程题目:PAT 1004. 成绩排名 (20)
查看>>
使用分层实现业务处理
查看>>
Microsoft Windows平台的NoSQL数据存储引擎
查看>>
浅谈虚拟机
查看>>
Ubuntu系统Linux编译osg库
查看>>
error MSB8008: 指定的平台工具集(v120)未安装或无效 解决办法
查看>>
BootstrapTable-导出数据
查看>>
Linux学习笔记 -- 系统目录结构
查看>>
[转载]ExtJs4 笔记(9) Ext.Panel 面板控件、 Ext.window.Window 窗口控件、 Ext.container.Viewport 布局控件...
查看>>
程序设计:找质数
查看>>
第三次作业结对编程
查看>>
Andorid Volley加载网络图片, 每次都会重新加载的问题
查看>>
php+layui数据表格实现数据分页渲染
查看>>
POJ-1077/HDU-1043
查看>>
pronunciation from Longman 2
查看>>
将数组排序组成最小的整数
查看>>