An n x n grid is filled with / \ or space. Each cell is divided into four triangles (0=top, 1=right, 2=bottom, 3=left). Count regions.

Input: ["/\\","\\/"] → Output: 4Input: ["//"," /"] → Output: 3

Treat each cell as 4 triangles. / divides top-left from bottom-right: union 0 with 3, union 1 with 2. \ divides top-right from bottom-left: union 0 with 1, union 2 with 3. Space: union all 4. Also union adjacent cell triangles.

class Solution { int[] parent; int count; public int regionsBySlashes(String[] grid) { int n = grid.length; parent = new int[4 * n * n]; count = 4 * n * n; for (int i = 0; i < parent.length; i++) parent[i] = i; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { char c = grid[i].charAt(j); int base = 4*(i*n+j); if (c == '/') { union(base,base+3); union(base+1,base+2); } else if (c == '\') { union(base,base+1); union(base+2,base+3); } else { union(base,base+1); union(base+1,base+2); union(base+2,base+3); } if (i+1<n) union(base+2, 4*((i+1)*n+j)); if (j+1<n) union(base+1, 4*(i*n+j+1)+3); } } return count; } private int find(int x) { return parent[x]==x?x:(parent[x]=find(parent[x])); } private void union(int a, int b) { int pa=find(a), pb=find(b); if (pa!=pb) { parent[pa]=pb; count--; } } }