AlgoDaily 22: Count the Planes

https://algodaily.com/challenges/count-the-planes

This is the same as the island counting problem.

function* enumerateGrid(grid) {
	if (!grid || grid.length < 1 || !grid[0].length) {
		return;
	}
	for (let x = 0; x < grid[0].length; x++) {
		for (let y = 0; y < grid[x].length; y++) {
			yield {x, y};
		}
	}
}

function* enumerateNeighbours(grid, x, y) {
	for (const p of [{x:-1,y:0},{x:0,y:-1},{x:1,y:0},{x:0,y:1}]) {
		if (grid[x+p.x] && grid[x+p.x][y+p.y]) {
			yield {x: x+p.x, y: y+p.y};
		}
	}
}

function visit(grid, x, y) {
	grid[x][y] = "V";
	for (const n of enumerateNeighbours(grid, x, y)) {
		if (grid[n.x] && grid[n.x][n.y] === "P") {
			visit(grid, n.x, n.y);
		}
	}
}

function numOfPlanes(grid) {
	let planesCount = 0;
	for (const p of enumerateGrid(grid)) {
		if (grid[p.x][p.y] === "P") {
			planesCount++;
			visit(grid, p.x, p.y);
		}
	}
	return planesCount;
}

You iterate over the grid cells. Each time you hit a “plane” cell, increment the counter, then recursively mark it and all its neighbouring “plane” cells as visited.


Tech mentioned