1. DFS Flood Fill on 3x3 Upscaled Grid
Intuition
Expand the n × n grid into a (3n) × (3n) binary matrix initialized to 0. For each character:
- '/': set (r*3+0, c*3+2), (r*3+1, c*3+1), (r*3+2, c*3+0) to 1.
- '': set (r*3+0, c*3+0), (r*3+1, c*3+1), (r*3+2, c*3+2) to 1.
Then run standard DFS flood fill over the (3n) × (3n) grid to count connected components of 0s.
Algorithm
- Let N = grid.length. Create a 3N × 3N matrix
gfilled with 0. - For each cell (r, c) in
grid: - If
grid[r][c] == '/': -
g[r*3][c*3 + 2] = 1,g[r*3 + 1][c*3 + 1] = 1,g[r*3 + 2][c*3] = 1 - Else if
grid[r][c] == '\': -
g[r*3][c*3] = 1,g[r*3 + 1][c*3 + 1] = 1,g[r*3 + 2][c*3 + 2] = 1 - Initialize
regions = 0. - For each cell (i, j) in 3N × 3N:
- If
g[i][j] == 0: -
regions++ - Run
dfs(i, j)to mark all 4-directionally reachable 0s as 1 (visited). - Return
regions.
#include <iostream>#include <vector>#include <string> void dfs(int r, int c, std::vector<std::vector<int>>& g, int size) { if (r < 0 || r >= size || c < 0 || c >= size || g[r][c] != 0) return; g[r][c] = 1; dfs(r - 1, c, g, size); dfs(r + 1, c, g, size); dfs(r, c - 1, g, size); dfs(r, c + 1, g, size);} int regionsBySlashesDFS(std::vector<std::string>& grid) { int n = grid.size(); int size = 3 * n; std::vector<std::vector<int>> g(size, std::vector<int>(size, 0)); for (int r = 0; r < n; ++r) { for (int c = 0; c < n; ++c) { if (grid[r][c] == '/') { g[r * 3][c * 3 + 2] = 1; g[r * 3 + 1][c * 3 + 1] = 1; g[r * 3 + 2][c * 3] = 1; } else if (grid[r][c] == '\\') { g[r * 3][c * 3] = 1; g[r * 3 + 1][c * 3 + 1] = 1; g[r * 3 + 2][c * 3 + 2] = 1; } } } int regions = 0; for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { if (g[i][j] == 0) { regions++; dfs(i, j, g, size); } } } return regions;} int main() { std::vector<std::string> grid = {" /", "/ "}; std::cout << "Regions (DFS): " << regionsBySlashesDFS(grid) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2) where N is grid.length. The upscaled grid has (3N)^2 = 9N^2 cells. For N = 30, 9*900 = 8100 cells, extremely fast. - Space complexity:
O(N^2) to store the 3N x 3N grid and recursion stack.