anoldvozer1710.v2
Senior Member
JavaScript:
function maxDistance(grid: number[][]): number {
const directions: number[][] = [[-1, 0], [0, -1], [1, 0], [0, 1]]
const isVisited = Array.from(Array(grid.length), () =>
Array(grid.length).fill(false)
);
const queue: number[][] = [];
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[0].length; col++) {
if (grid[row][col] === 1) {
queue.push([row, col]);
isVisited[row][col] = true;
}
}
}
let dis = -1;
while (queue.length > 0) {
const currentLength = queue.length;
for (let i = 0; i < currentLength; i++) {
const [x, y] = queue.shift();
for (const direction of directions) {
const row = x + direction[0];
const col = y + direction[1];
if (row >= 0 && col >= 0 && row < grid.length && col < grid[0].length && !isVisited[row][col]
) {
queue.push([row, col]);
isVisited[row][col] = true;
}
}
}
dis++;
}
return dis === 0 ? -1 : dis;
};
, hoặc là một data structure nào bất kì
bác ạ bác có tài liệu cho em xin ì



