当前位置: 首页 > news >正文

【hot100】054螺旋矩阵

一、思路

这个题目主要有两个问题,一是什么时候切换方向,二是如何切换方向

问题一:此步移动完后,判断下一个元素,如果大于等于边界值(从0开始)或者小于边界值时或者访问数组为真时

问题二:创建一个方向数组,通过行数和列数的加减来实现切换方向,然后通过%4来循环访问这个数组

二、记忆

1.二维矩阵的使用长度声明和直接用数值定义

int[][] check = new int[rows][columns];
int[][] nextdirections ={{0,1},{1,0},{0,-1},{-1,0}};

2.方向数组来确定移动方向的思路

3.预判定的思路

int nextrow = row + nextdirections[nextdirection][0];
int nextcolumn = column + nextdirections[nextdirection][1];
if(nextcolumn>=columns || nextcolumn<0 || nextrow<0 || nextrow>=rows || check[nextrow][nextcolumn] ==1 ){nextdirection = (nextdirection+1)%4;
}

三、代码

public List<Integer> spiralOrder(int[][] matrix){ArrayList<Integer> order = new ArrayList<>();//异常条件处理if(matrix == null || matrix.length == 0 || matrix[0].length ==0) return order;int rows = matrix.length,columns = matrix[0].length;int[][] check = new int[rows][columns];int[][] nextdirections ={{0,1},{1,0},{0,-1},{-1,0}};int total = rows*columns;int row = 0,column = 0;int nextdirection = 0;for(int i = 0;i<total;i++){order.add(matrix[row][column]);check[row][column] = 1;//预判,确定移动方向int nextrow = row + nextdirections[nextdirection][0];int nextcolumn = column + nextdirections[nextdirection][1];if(nextcolumn>=columns || nextcolumn<0 || nextrow<0 || nextrow>=rows || check[nextrow][nextcolumn] ==1 ){nextdirection = (nextdirection+1)%4;}//移动row += nextdirections[nextdirection][0];column += nextdirections[nextdirection][1];}return order;}

http://www.lryc.cn/news/537365.html

相关文章:

  • 【Java学习】类和对象
  • TestHubo基础教程-创建项目
  • JS 链表
  • 数据结构(陈越,何钦铭)第三讲 树(上)
  • 企业文件安全:零信任架构下的文件访问控制
  • 性格测评小程序06用户注册校验
  • $符(前端)
  • Windows 11如何显示全部右键菜单?
  • 离线量化算法和工具 --学习记录1
  • python第七课
  • 华为IPD简介
  • 如何在Spring Boot中配置分布式配置中心
  • Golang internals
  • 天翼云910B部署DeepSeek蒸馏70B LLaMA模型实践总结
  • 数据治理常用的开源项目有哪些?
  • 数据结构与算法之排序算法-(计数,桶,基数排序)
  • Word正文中每两个字符之间插入一个英文半角空格
  • 把 DeepSeek1.5b 部署在显卡小于4G的电脑上
  • A4988一款带转换器和过流保护的 DMOS 微步驱动器的使用方式
  • 一口井深7米,一只蜗牛从井底往上爬每天爬3米掉下去1米,问几天能爬上井口?
  • Asp.Net Core MVC 中级开发教程
  • Windows上安装Go并配置环境变量(图文步骤)
  • C++效率掌握之STL库:string底层剖析
  • 【Erdas实验教程】004:影像镶嵌拼接
  • SpringMVC 请求参数接收
  • [高等数学]换元积分法
  • Redis简介、常用命令及优化
  • 大模型训练为什么依赖GPU
  • 帕金森病与三叉神经痛的基因关联分析
  • 【Android开发】华为手机安装包安装失败“应用是非正式版发布版本,当前设备不支持安装”问题解决