// check if index is within range
function* neighbors(r, c, N) {
const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
for (const [dr, dc] of directions) {
const nr = r + dr;
const nc = c + dc;
if (0 <= nr && nr < N && 0 <= nc && nc < N) {
yield [nr, nc];
}
}
}
// dfs to calculate length of path
function dfs(R, C, index, grid, N) {
let ans = 1;
grid[R][C] = index;
for (const [nr, nc] of neighbors(R, C, N)) {
if (grid[nr][nc] == 1) {
ans += dfs(nr, nc, index, grid, N);
}
}
return ans;
}
// function to return largest possible length of Path
function largestPath(grid) {
const N = grid.length;
const area = {};
let index = 2;
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
if (grid[i][j] == 1) {
area[index] = dfs(i, j, index, grid, N);
index += 1;
}
}
}
let ans = Math.max(...Object.values(area), 0);
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
if (grid[i][j] == 0) {
const seen = new Set();
for (const [nr, nc] of neighbors(i, j, N)) {
if (grid[nr][nc] > 1) {
seen.add(grid[nr][nc]);
}
}
ans = Math.max(ans, 1 + [...seen].reduce((acc, val) => acc + area[val], 0));
}
}
}
// return maximum possible length
return ans;
}
// Driver code
const I = [[1, 0], [0, 1]];
// Function call to print answer
console.log(largestPath(I));