1162. As Far from Land as Possible
Medium
Given an n x n
grid
containing only values 0
and 1
, where 0
represents water and 1
represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1
.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0)
and (x1, y1)
is |x0 - x1| + |y0 - y1|
.
Example 1:
Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.
Example 2:
Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 100
grid[i][j]
is0
or1
๋ฌธ์
grid[i] === 0 // ๋ฌผ
grid[i] === 1 // ๋
๋ ์์ ๊ฐ์ฅ ๋ฉ๋ฆฌ ๋จ์ด์ง ๋ฌผ๊น์ง์ ๊ฑฐ๋ฆฌ ์ฐพ๋ ๋ฌธ์
๋ฌธ์ ์ ๊ทผ๋ฒ
๋์์ ํ์ํด์ผํ๊ธฐ ๋๋ฌธ์ BFS ์ฌ์ฉํ์ฌ ํ์ด
๋ชจ๋ ๋ ์์ ๋์์ ํ์์ ์งํํ๋ฉด์ ์ต๋ ๊ฑฐ๋ฆฌ๋ฅผ ์ฐพ๋๋ค.
manhattan distance ์ฌ์ฉ x
์์ฌ ์ฝ๋
- ๋ณ์ queue์ ๋ฐฐ์ด์ ์ด๊ธฐํํ๊ณ grid๋ฅผ ์ํํ๋ฉด์ ๋ ์ ์ขํ์ ๊ฑฐ๋ฆฌ 0์ ํธ์ํด ์ค๋ค.
- maxDistance๋ฅผ ๋ํ๋ด๋ ๋ณ์๋ฅผ ์ ์ธํ๊ณ -1๋ก ์ด๊ธฐํํด ์ค๋ค.
- BFS ํ์
- maxDistance ์ ๋ฐ์ดํธ
- 4๊ฐ์ง ๋ฐฉํฅ์ผ๋ก ํ์์ ํ๋ฉฐ grid๊ฐ ์ ํจํ์ง ์ฒดํฌํ๋ค
- ์ด๋ํ ์ขํ๊ฐ ์ ํจํ๋ค๋ฉด grid์์ ํด๋น ์์น๋ฅผ ๋ ์ผ๋ก ๋ณ๊ฒฝํ๊ณ queue์ ํธ์ํด ์ค๋ค.
- maxDistance๋ฅผ ๋ฆฌํดํ๋ค. ์ด๋ maxDistance๊ฐ 0์ด๋ผ๋ฉด ์ก์ง ๋๋ ๋ฌผ์ด ์๋ค๊ณ ํ๋จํ์ฌ -1์ ๋ฆฌํดํด์ค๋ค.
/**
* @param {number[][]} grid
* @return {number}
*/
var maxDistance = function(grid) {
const m = grid.length, n = grid[0].length
const directions = [[-1,0],[0,1],[1,0],[0,-1]]
// grid์์ ๋ฐฉํฅ์ด๋ํ ๋ ์ ํจํ์ง ์ฒดํฌ
const gridIsValid = (x,y) => {
return x >= 0 && x < m && y >= 0 && y < n && grid[x][y] === 0
}
let queue = []
// ๋
์ ์์น๋ฅผ ์ฐพ์์ queue์ push
for(let row=0; row<m; row++){
for(let col=0; col<n; col++){
if(grid[row][col] === 1) {
queue.push([row,col,0])
}
}
}
let maxDistance = -1
while(queue.length){
const nextQueue = []
for(const [x,y,distance] of queue){
maxDistance = Math.max(maxDistance, distance)
for(const [dx,dy] of directions){
const nx = x + dx, ny = y + dy
if(gridIsValid(nx,ny)){
grid[nx][ny] = 1
nextQueue.push([nx,ny,distance+1])
}
}
}
queue = nextQueue
}
return maxDistance === 0 ? -1 : maxDistance
};
'๐ Study Note > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
542. 01 Matrix (0) | 2023.02.14 |
---|---|
2306. Naming a Company (0) | 2023.02.09 |
904. Fruit Into Baskets (0) | 2023.02.07 |
1091. Shortest Path in Binary Matrix (0) | 2023.02.06 |
2091. Removing Minimum and Maximum From Array (0) | 2023.02.01 |