Skip to content

Commit 178b8a7

Browse files
committed
Add solution #1162
1 parent 30caeb7 commit 178b8a7

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,159 LeetCode solutions in JavaScript
1+
# 1,160 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -908,6 +908,7 @@
908908
1157|[Online Majority Element In Subarray](./solutions/1157-online-majority-element-in-subarray.js)|Hard|
909909
1160|[Find Words That Can Be Formed by Characters](./solutions/1160-find-words-that-can-be-formed-by-characters.js)|Easy|
910910
1161|[Maximum Level Sum of a Binary Tree](./solutions/1161-maximum-level-sum-of-a-binary-tree.js)|Medium|
911+
1162|[As Far from Land as Possible](./solutions/1162-as-far-from-land-as-possible.js)|Medium|
911912
1189|[Maximum Number of Balloons](./solutions/1189-maximum-number-of-balloons.js)|Easy|
912913
1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy|
913914
1206|[Design Skiplist](./solutions/1206-design-skiplist.js)|Hard|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* 1162. As Far from Land as Possible
3+
* https://leetcode.com/problems/as-far-from-land-as-possible/
4+
* Difficulty: Medium
5+
*
6+
* Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents
7+
* land, find a water cell such that its distance to the nearest land cell is maximized, and return
8+
* the distance. If no land or water exists in the grid, return -1.
9+
*
10+
* The distance used in this problem is the Manhattan distance: the distance between two cells
11+
* (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
12+
*/
13+
14+
/**
15+
* @param {number[][]} grid
16+
* @return {number}
17+
*/
18+
var maxDistance = function(grid) {
19+
const size = grid.length;
20+
const queue = [];
21+
let waterCount = 0;
22+
23+
for (let row = 0; row < size; row++) {
24+
for (let col = 0; col < size; col++) {
25+
if (grid[row][col] === 1) {
26+
queue.push([row, col]);
27+
} else {
28+
waterCount++;
29+
}
30+
}
31+
}
32+
33+
if (waterCount === 0 || queue.length === 0) return -1;
34+
35+
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
36+
let distance = -1;
37+
38+
while (queue.length > 0) {
39+
distance++;
40+
const levelSize = queue.length;
41+
for (let i = 0; i < levelSize; i++) {
42+
const [currentRow, currentCol] = queue.shift();
43+
for (const [deltaRow, deltaCol] of directions) {
44+
const newRow = currentRow + deltaRow;
45+
const newCol = currentCol + deltaCol;
46+
if (newRow >= 0 && newRow < size && newCol >= 0 && newCol < size
47+
&& grid[newRow][newCol] === 0) {
48+
grid[newRow][newCol] = 1;
49+
queue.push([newRow, newCol]);
50+
}
51+
}
52+
}
53+
}
54+
55+
return distance === 0 ? -1 : distance;
56+
};

0 commit comments

Comments
 (0)