当前位置:网站首页>剑指 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;
}
}
边栏推荐
- [bw16 application] Anxin can realize mqtt communication with bw16 module / development board at instruction
- Windows starts redis service
- MongoDB怎么实现创建删除数据库、创建删除表、数据增删改查
- 印象笔记终于支持默认markdown预览模式
- JS judge whether checkbox is selected in the project
- Huawei HCIP - datacom - Core 03 jours
- Unity uses mesh to realize real-time point cloud (I)
- How to become a senior digital IC Design Engineer (5-2) theory: ULP low power design technology (Part 1)
- VSCode+mingw64
- 根据热门面试题分析Android事件分发机制(二)---事件冲突分析处理
猜你喜欢
随机推荐
How to speed up video playback in browser
Detailed explanation of diffusion model
The configuration and options of save actions are explained in detail, and you won't be confused after reading it
消费互联网的产业链其实是很短的,它仅仅承接平台上下游的对接和撮合的角色
shake数据库中怎么使用Mongo-shake实现MongoDB的双向同步啊?
二叉树高频题型
Add new item after the outbound delivery order of SAP mm sto document is created?
(3/8) method parameters of improper use of enumeration (2)
Where is the answer? action config/Interceptor/class/servlet
Netease Cloud Wechat applet
第一讲:寻找矩阵的极小值
Oracle installation enhancements error
Huawei hcip datacom core_ 03day
NETCORE 3.1 solves cross domain problems
进程间的通信方式
js逆向教程第二发-猿人学第一题
flinkcdc 用sqlclient可以指定mysqlbinlog id执行任务吗
Can flycdc use SqlClient to specify mysqlbinlog ID to execute tasks
Sublime Text4 download the view in bower and set the shortcut key
浏览器中如何让视频倍速播放