Skip to content

Commit 2973188

Browse files
LeetCode problem Flood Fill and Rotting Oranges
1 parent 9e90f21 commit 2973188

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// LeetCode: 733. Flood Fill
2+
const floodFill = (image, sr, sc, color) => {
3+
const rows = image.length;
4+
const cols = image[0].length;
5+
const originalColor = image[sr][sc];
6+
if (originalColor === color) {
7+
return image;
8+
}
9+
const dfs = (row, col) => {
10+
if (
11+
row < 0 ||
12+
row >= rows ||
13+
col < 0 ||
14+
col >= cols ||
15+
image[row][col] !== originalColor
16+
) {
17+
return;
18+
}
19+
image[row][col] = color;
20+
21+
dfs(row + 1, col); // Down
22+
dfs(row - 1, col); // Up
23+
dfs(row, col + 1); // Right
24+
dfs(row, col - 1); // Left
25+
};
26+
dfs(sr, sc);
27+
return image;
28+
};
29+
const image = [
30+
[1, 1, 1],
31+
[1, 1, 0],
32+
[1, 0, 1],
33+
];
34+
const sr = 1,
35+
sc = 1,
36+
color = 2;
37+
console.log(floodFill(image, sr, sc, color)); // Output: [[2, 2, 2], [2, 2, 0], [2, 0, 1]]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// LeetCode: 994. Rotting Oranges
2+
const orangesRotting = (grid) => {
3+
const rows = grid.length;
4+
const cols = grid[0].length;
5+
const directions = [
6+
[1, 0], // Down
7+
[-1, 0], // Up
8+
[0, 1], // Right
9+
[0, -1], // Left
10+
];
11+
12+
let queue = []; // To store the rotten oranges with their timestamps
13+
let freshCount = 0;
14+
15+
// Initialize the queue with all rotten oranges and count fresh oranges
16+
for (let r = 0; r < rows; r++) {
17+
for (let c = 0; c < cols; c++) {
18+
if (grid[r][c] === 2) {
19+
queue.push([r, c, 0]); // [row, col, minutes]
20+
} else if (grid[r][c] === 1) {
21+
freshCount++;
22+
}
23+
}
24+
}
25+
26+
let minutes = 0;
27+
28+
// Perform BFS
29+
while (queue.length > 0) {
30+
const [row, col, time] = queue.shift();
31+
minutes = time;
32+
33+
// Check all 4-directionally adjacent cells
34+
for (const [dr, dc] of directions) {
35+
const newRow = row + dr;
36+
const newCol = col + dc;
37+
38+
// If the adjacent cell is a fresh orange, rot it
39+
if (
40+
newRow >= 0 &&
41+
newRow < rows &&
42+
newCol >= 0 &&
43+
newCol < cols &&
44+
grid[newRow][newCol] === 1
45+
) {
46+
grid[newRow][newCol] = 2; // Mark it as rotten
47+
freshCount--; // Decrease fresh orange count
48+
queue.push([newRow, newCol, time + 1]); // Add it to the queue with the new timestamp
49+
}
50+
}
51+
}
52+
53+
// If there are still fresh oranges left, return -1
54+
return freshCount === 0 ? minutes : -1;
55+
};
56+
57+
const grid1 = [
58+
[2, 1, 1],
59+
[1, 1, 0],
60+
[0, 1, 1],
61+
];
62+
console.log(orangesRotting(grid1)); // Output: 4

0 commit comments

Comments
 (0)