分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

螺旋矩阵的获取,原型在https://leetcode.com/articles/spiral-matrix/

发布时间:2023-09-06 02:24责任编辑:沈小雨关键词:http

今天看了个题目很有意思,原型在https://leetcode.com/articles/spiral-matrix/

摘要如下:

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:[ ?[1, 2, 3, 4], ?[5, 6, 7, 8], ?[9,10,11,12]]Output: [1,2,3,4,8,12,11,10,9,5,6,7]
具体意思大致就是,给你一个m*n的二维数组,然后顺时针旋转获取里面的值,看了它后面的很多传统代码,反正就是用了很多控制,判断语句才把结果求出来,并且效率很低,不便于理解;

而随着脚本语言越来越越流行了,我试着用js的形参可以传方法,数组可以保存方法的特性把它写下来,节省了大量的思考和开销,执行效率很高,并且易于理解,供以后参考(自己测试了都是10ms以内给结果的,哈哈);
--------------------------------------------------------------------
思路:
1.因为是顺时针取数,所以定义四个方法right,down,left,up把它存入数组中,头shift()执行完push()到尾部,构成一个循环;
2.因为有边界,定义一个对象有right,left,top,bottom四个属性,供方法执行共享
3.遍历直到边界收缩为0;
 1 /** 2 ?* 矩阵螺旋取数 3 ?*/ 4 const spiralOrder=function(matrix){ 5 ????let orderPos={ 6 ????????????left:0, 7 ????????????right:matrix[0].length-1, 8 ????????????top:0, 9 ????????????bottom:matrix.length-110 ????}11 ????let functionSequence=[toRigth,toDown,toLeft,toUp]12 ????let result=[];13 ????while(orderPos.left<=orderPos.right&&orderPos.top<=orderPos.bottom){14 ????????doswitch(functionSequence.shift());15 ????}16 ????return result;17 ????function doswitch(currentf){18 ????????currentf(result,matrix,orderPos)19 ????????functionSequence.push(currentf)20 ????}21 ????function toRigth(result,matrix,orderPos){22 ????????for(let i=orderPos.left;i<=orderPos.right;i++){23 ????????????result.push(matrix[orderPos.top][i])24 ????????}25 ????????orderPos.top+=1;26 ????}27 ????function toDown(result,matrix,orderPos){28 ????????for(let i=orderPos.top;i<=orderPos.bottom;i++){29 ????????????result.push(matrix[i][orderPos.right])30 ????????}31 ????????orderPos.right-=1;32 ????}33 ????function toLeft(result,matrix,orderPos){34 ????????for(let i=orderPos.right;i>=orderPos.left;i--){35 ????????????result.push(matrix[orderPos.bottom][i])36 ????????}37 ????????orderPos.bottom-=1;38 ????}39 ????function toUp(result,matrix,orderPos){40 ????????for(let i=orderPos.bottom;i>=orderPos.top;i--){41 ????????????result.push(matrix[i][orderPos.left])42 ????????}43 ????????orderPos.left+=1;44 ????}45 }46 spiralOrder([[1,2,3],[4,5,6],[7,8,9]]);
View Code





螺旋矩阵的获取,原型在https://leetcode.com/articles/spiral-matrix/

原文地址:https://www.cnblogs.com/376346295-blog/p/10034091.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved