当前位置:网站首页>剑指 Offer II 107. 矩阵中的距离
剑指 Offer II 107. 矩阵中的距离
2022-07-07 07:07:00 【彼淇梁】
剑指 Offer II 107. 矩阵中的距离【中等题】
思路:
采用BFS层序遍历,找出所有的元素0,从元素0开始向四个方向层序遍历,设ans数组存储最近0距离,则ans中,mat矩阵元素0位置值为0,每层遍历遇到1则将ans值更新为元素0的ans值+1
代码:
class Solution {
static int[][] ans;
static int[][] dir = {
{
0,-1},{
0,1},{
-1,0},{
1,0}};
static int m,n;
public static int[][] updateMatrix(int[][] mat) {
m = mat.length;
n = mat[0].length;
//标记mat矩阵(i,j)位置元素是否被搜索过
boolean[][] seen = new boolean[m][n];
//存储mat矩阵中的0的位置坐标
Queue<int[]> queue = new LinkedList<>();
//存储mat矩阵(i,j)位置元素最近的0的距离
ans = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 0){
//将mat矩阵中元素0的位置坐标压入队列
queue.offer(new int[]{
i,j});
//标记当前位置已被搜索过
seen[i][j] = true;
}
}
}
//BFS遍历,当栈中元素为空时,循环结束
while(!queue.isEmpty()){
//取出队列顶部元素0的位置
int[] cell = queue.poll();
//取出元素0的坐标
int i = cell[0],j = cell[1];
for (int k = 0; k < 4; k++) {
//对元素0进行上下左右四个方向搜索,搜索到的位置坐标为(x,y)
int x = i + dir[k][0],y = j + dir[k][1];
//如果(x,y)未超出矩阵边界且(x,y)位置未被搜索过
if (x >= 0 && x < m && y >= 0 && y < n && !seen[x][y]){
//ans的(x,y)位置值 等于 ans的(i,j)位置值 + 1
ans[x][y] = ans[i][j] + 1;
//将(x,y)位置压入队列
queue.offer(new int[]{
x,y});
//将(x,y)位置标记为已搜索
seen[x][y] = true;
}
}
}
return ans;
}
}
边栏推荐
- Zen - batch import test cases
- 数据库多表关联查询问题
- Dynamics 365online applicationuser creation method change
- Difference between interface iterator and iteratable
- js逆向教程第二发-猿人学第一题
- sql 里面使用中文字符判断有问题,哪位遇到过?比如value&lt;&gt;`无`
- nlohmann json
- Unity shader (learn more about vertex fragment shaders)
- PostgreSQL创建触发器的时候报错,
- How to become a senior digital IC Design Engineer (5-2) theory: ULP low power design technology (Part 1)
猜你喜欢

沙龙预告|GameFi 领域的瓶颈和解决方案

Information Security Experiment 1: implementation of DES encryption algorithm

网易云微信小程序

How to use clipboard JS library implements copy and cut function

Jmeters use

Sublime Text4 download the view in bower and set the shortcut key

First issue of JS reverse tutorial

Install pyqt5 and Matplotlib module

十二、排序

JS reverse tutorial second issue - Ape anthropology first question
随机推荐
Jmeters use
AI从感知走向智能认知
JS inheritance prototype
flinkcdc 用sqlclient可以指定mysqlbinlog id执行任务吗
The use of recycling ideas
What is MD5
沙龙预告|GameFi 领域的瓶颈和解决方案
flinkcdc采集oracle在snapshot阶段一直失败,这个得怎么调整啊?
如何成为一名高级数字 IC 设计工程师(1-6)Verilog 编码语法篇:经典数字 IC 设计
[4g/5g/6g topic foundation-146]: Interpretation of white paper on 6G overall vision and potential key technologies-1-overall vision
liunx命令
La différence entre viewpager 2 et viewpager et la mise en œuvre de la rotation viewpager 2
csdn涨薪技术-浅学Jmeter的几个常用的逻辑控制器使用
Liunx command
Unity shader (learn more about vertex fragment shaders)
根据热门面试题分析Android事件分发机制(一)
JS judge whether checkbox is selected in the project
Unity3d interface is embedded in WPF interface (mouse and keyboard can respond normally)
Unity shader (basic concept)
Where is the answer? action config/Interceptor/class/servlet