
leetcode做题记录0059
发布日期:2021-05-07 13:48:26
浏览次数:11
分类:原创文章
本文共 1756 字,大约阅读时间需要 5 分钟。
leetcode 0059
说明
只是为了记录一下,不求多快,也不深究。
会简要描述思路,代码中不写注释。
如碰到不会做的用了别人代码会在博客中标出。
题目描述
思路
这题跟第54题一样,模拟一下手动插入的过程就行了,就从第一个坐标位置开始,算出下一个坐标位置,直到结束。
class Solution { private final int RIGHT = 1; private final int LEFT = 2; private final int DOWN = 3; private final int TOP = 4; private int status; public int[][] generateMatrix(int n) { this.status = RIGHT; int[] border = { 0, n - 1, 0, n - 1 }; int[] idx = { 0, 0 }; int count = 1; int[][] matrix = new int[n][n]; while (idx[0] != -1) { matrix[idx[0]][idx[1]] = count; count++; idx = nextIdx(border, idx); } return matrix; } private int[] nextIdx(int[] border, int[] idx) { switch (status) { case (RIGHT): { if (idx[1] == border[3]) { if (idx[0] == border[1]) { return new int[] { -1, -1 }; } border[0]++; status = DOWN; return new int[] { idx[0] + 1, idx[1] }; } return new int[] { idx[0], idx[1] + 1 }; } case (LEFT): { if (idx[1] == border[2]) { if (idx[0] == border[0]) { return new int[] { -1, -1 }; } border[1]--; status = TOP; return new int[] { idx[0] - 1, idx[1] }; } return new int[] { idx[0], idx[1] - 1 }; } case (TOP): { if (idx[0] == border[0]) { if (idx[1] == border[3]) { return new int[] { -1, -1 }; } border[2]++; status = RIGHT; return new int[] { idx[0], idx[1] + 1 }; } return new int[] { idx[0] - 1, idx[1] }; } case (DOWN): { if (idx[0] == border[1]) { if (idx[1] == border[2]) { return new int[] { -1, -1 }; } border[3]--; status = LEFT; return new int[] { idx[0], idx[1] - 1 }; } return new int[] { idx[0] + 1, idx[1] }; } default: return new int[] { -1, -1 }; } }}
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2025年03月23日 13时01分00秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Python语言'类'概念再理解
2019-03-04
(2019.6.27)Anaconda清华镜像已恢复使用
2019-03-04
Robomongo使用教程:踩着前辈的路
2019-03-04
Python中Class类与def函数的区别
2019-03-04
OpenAI Gym简介及初级实例
2019-03-04
用Matplotlib和Gym优雅地呈现股票交易智体
2019-03-04
Github上量化交易相关项目汇总
2019-03-04
JS取出两个数组中的不同或相同元素
2019-03-04
Ubuntu 18.04 zip压缩文件及其文件 夹中的所以 内容
2019-03-04
int 转 CString
2019-03-04
Edit编辑框自动换行与长度
2019-03-04
如何在Windows上搭建NFS服务器实现开发板与Windows之间的文件共享
2019-03-04
英语02_单词词性
2019-03-04
C语言08_数组[ Array ]
2019-03-04
C语言12_预处理 #
2019-03-04
低通滤波器的设计
2019-03-04
窄带随机过程的产生
2019-03-04
随机四则运算
2019-03-04
Maven
2019-03-04