[Algorithm] Print 2-D array in spiral order
The idea to solve the problem is set five variable, first direction, we need to switch direction after we finish printing one row or one column.
dir = (dir+1) % 4
Then set four boundry, top, left, right, bottom:
let results = [], dir = 0, //0: left -> right, 1: top -> bottom, 2: right -> left, 3: bottom -> top top = 0, bottom = arys.length - 1, left = 0, right = arys[0].length - 1;
Each time finish printing a row or a column, modify the boundry accordingly:
function PrintSpiralOrder (arys) { let results = [], dir = 0, //0: left -> right, 1: top -> bottom, 2: right -> left, 3: bottom -> top top = 0, bottom = arys.length - 1, left = 0, right = arys[0].length - 1; while (top <= bottom && left <= right) { if (dir === 0) { for (let i = left; i <= right; i++) { results.push(arys[top][i]); } top++; } else if (dir === 1) { for (let i = top; i <= bottom; i++) { results.push(arys[i][right]); } right--; } else if (dir === 2) { for (let i = right; i >= left; i--) { results.push(arys[bottom][i]); } bottom--; } else if (dir === 3) { for (let i = bottom; i >= top; i--) { results.push(arys[i][left]); } left++; } dir = (dir + 1) % 4; } return results; } const data = [ [2,4,6,8], [5,9,12,16], [2,11,5,9], [3,2,1,8] ]; const res = PrintSpiralOrder(data); console.log(res); // [ 2, 4, 6, 8, 16, 9, 8, 1, 2, 3, 2, 5, 9, 12, 5, 11 ]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-03-28 [Grid Layout] Use auto-fill and auto-fit if the number of repeated grid tracks is not to be def
2017-03-28 [Grid Layout] Use the repeat function to efficiently write grid-template values
2017-03-28 [Grid Layout] Use the minmax function to specify dynamically-sized tracks
2017-03-28 [Jest] Snapshot
2017-03-28 [Flow] More tips about Flow
2017-03-28 [Grid Layout] Describe a grid layout using grid-template-areas
2016-03-28 [Angular 2] @Input Custom public property naming