const dx = [-1, 0, 1, 0]; const dy = [0, 1, 0, -1]; let n, m;
constfindNearestLand = (x, y, grid) => { let vis = {}; let q = []; q.push({x, y, step: 0}); vis[`${x}${y}`] = 1; while(q.length > 0) { let f = q.shift(); for (let i = 0; i < 4; i++) { const nx = f.x + dx[i], ny = f.y + dy[i]; if (!(nx >= 0 && nx <= n -1 && ny >= 0 && ny <= m - 1)) { continue; } if (!vis[`${nx}${ny}`]) { if (grid[nx][ny]) { return f.step + 1; } q.push({ x: nx, y: ny, step: f.step + 1 }); vis[`${nx}${ny}`] = 1; } } } return -1; };
var maxDistance = function(grid) { n = grid.length; m = grid[0].length; let ans = -1; for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (!grid[i][j]) { ans = Math.max(ans, findNearestLand(i, j, grid)); } } } return ans; };