当前位置:网站首页>Breadth first search rotten orange
Breadth first search rotten orange
2022-07-06 10:38:00 【GUTSZ】
Breadth first search rotten orange
problem :
Code :
class pair{
int x;
int y;
public pair(int x,int y){
this.x=x;
this.y=y;
}
}
class Solution {
public int orangesRotting(int[][] grid) {
if (grid.length == 0)
return 0;
int row = grid.length;
int col = grid[0].length;
Queue<pair> q = new LinkedList<>();
// Find the bad fruit , The team
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == 2)
q.offer(new pair(i, j));
}
}
int[][] nextp = {
{
1, 0}, {
-1, 0}, {
0, 1}, {
0, -1}};
int step = 0;
while (!q.isEmpty()) {
int size = q.size();
boolean flag = false;
while (size-- != 0) {
pair cur = q.poll();
// Search for a new location
for (int i = 0; i < 4; i++) {
int nx = cur.x + nextp[i][0];
int ny = cur.y + nextp[i][1];
if (nx >= row || nx < 0 || ny >= col || ny < 0)
continue;
if (grid[nx][ny] == 1) {
flag = true;
grid[nx][ny] = 2;
q.offer(new pair(nx, ny));
}
}
}
if (flag)
step++;
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == 1)
return -1;
}
}
return step;
}
}
Running results :
边栏推荐
- MySQL实战优化高手11 从数据的增删改开始讲起,回顾一下Buffer Pool在数据库里的地位
- A necessary soft skill for Software Test Engineers: structured thinking
- Download and installation of QT Creator
- Mysql35 master slave replication
- MySQL28-数据库的设计规范
- Mysql30 transaction Basics
- pytorch的Dataset的使用
- MySQL transaction log
- MySQL26-性能分析工具的使用
- Adaptive Bezier curve network for real-time end-to-end text recognition
猜你喜欢
该不会还有人不懂用C语言写扫雷游戏吧
Just remember Balabala
MySQL35-主从复制
MySQL24-索引的数据结构
MySQL23-存儲引擎
A necessary soft skill for Software Test Engineers: structured thinking
Mysql35 master slave replication
Water and rain condition monitoring reservoir water and rain condition online monitoring
Mysql23 storage engine
实现微信公众号H5消息推送的超级详细步骤
随机推荐
[Julia] exit notes - Serial
Just remember Balabala
软件测试工程师必备之软技能:结构化思维
pytorch的Dataset的使用
Sed text processing
MySQL30-事务基础知识
MySQL27-索引优化与查询优化
Introduction tutorial of typescript (dark horse programmer of station B)
Texttext data enhancement method data argument
Mysql23 storage engine
Use JUnit unit test & transaction usage
MySQL22-逻辑架构
text 文本数据增强方法 data argumentation
February 13, 2022 - Maximum subarray and
MySQL combat optimization expert 03 uses a data update process to preliminarily understand the architecture design of InnoDB storage engine
Super detailed steps to implement Wechat public number H5 Message push
A necessary soft skill for Software Test Engineers: structured thinking
高并发系统的限流方案研究,其实限流实现也不复杂
使用OVF Tool工具从Esxi 6.7中导出虚拟机
Global and Chinese market of transfer switches 2022-2028: Research Report on technology, participants, trends, market size and share