forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
38 lines (37 loc) · 1.18 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
private int[] dirs = {-1, 0, 1, 0, -1};
public int getFood(char[][] grid) {
int m = grid.length, n = grid[0].length;
Deque<int[]> q = new ArrayDeque<>();
for (int i = 0, x = 1; i < m && x == 1; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '*') {
q.offer(new int[] {i, j});
x = 0;
break;
}
}
}
int ans = 0;
while (!q.isEmpty()) {
++ans;
for (int t = q.size(); t > 0; --t) {
var p = q.poll();
for (int k = 0; k < 4; ++k) {
int x = p[0] + dirs[k];
int y = p[1] + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n) {
if (grid[x][y] == '#') {
return ans;
}
if (grid[x][y] == 'O') {
grid[x][y] = 'X';
q.offer(new int[] {x, y});
}
}
}
}
}
return -1;
}
}