当前位置:网站首页>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 :
边栏推荐
猜你喜欢

The underlying logical architecture of MySQL

MySQL32-锁

Opencv uses freetype to display Chinese

Mysql30 transaction Basics

Jar runs with error no main manifest attribute

Complete web login process through filter

Ueeditor internationalization configuration, supporting Chinese and English switching

Export virtual machines from esxi 6.7 using OVF tool

MySQL combat optimization expert 12 what does the memory data structure buffer pool look like?

软件测试工程师必备之软技能:结构化思维
随机推荐
Global and Chinese market of thermal mixers 2022-2028: Research Report on technology, participants, trends, market size and share
第一篇博客
实现微信公众号H5消息推送的超级详细步骤
Google login prompt error code 12501
MySQL real battle optimization expert 11 starts with the addition, deletion and modification of data. Review the status of buffer pool in the database
MySQL33-多版本并发控制
软件测试工程师必备之软技能:结构化思维
[C language] deeply analyze the underlying principle of data storage
Use of dataset of pytorch
MySQL34-其他数据库日志
Good blog good material record link
Pytorch LSTM实现流程(可视化版本)
Mysql28 database design specification
Security design verification of API interface: ticket, signature, timestamp
Mysql30 transaction Basics
Sed text processing
MySQL实战优化高手06 生产经验:互联网公司的生产环境数据库是如何进行性能测试的?
API learning of OpenGL (2001) gltexgen
MySQL20-MySQL的数据目录
Mysql35 master slave replication