959. Regions Cut By Slashes

202408281709
tags: #dfs

var regionsBySlashes = function(grid) {
	const n = grid.length;
	let regions = 0;
	const g = new Array(n * 3).fill().map(() => new Array(n * 3));

	const dfs = (i, j) => {
		if (i < 0 || i >= g.length || j < 0 || j >= g[0].length || g[i][j] === 1) {
			return 0;
		}
		g[i][j] = 1;
		return 1 + dfs(i + 1, j) + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i, j - 1);
	}
	
	for (let i = 0; i < n; i++) {
		for (let j = 0; j < n; j++) {
			if (grid[i][j] === '/') {
				g[i * 3][j * 3 + 2] = 1;
				g[i * 3 + 1][j * 3 + 1] = 1;
				g[i * 3 + 2][j * 3] = 1;
			}
			else if (grid[i][j] === '\\') {
				g[i * 3][j * 3] = 1;
				g[i * 3 + 1][j * 3 + 1] = 1;
				g[i * 3 + 2][j * 3 + 2] = 1;
			}
		}
	}
	
	for (let i = 0; i < g.length; i++) {
		for (let j = 0; j < g.length; j++) {
			if (dfs(i, j) > 0) {
				regions += 1;
			}
		}
	}
	return regions;
};

Reference

https://leetcode.com/problems/regions-cut-by-slashes