You are given a 2D grid. A '#' represents an obstacle and a '.' represents free space. You need to find the areas of the disconnected components. The cells (i+1, j), (i, j+1), (i-1, j), (i, j-1) are the adjacent to the cell (i, j).
Example:
Input: row=3, col=3,grid = { { '#', '#', '.' }, { '.', '.', '#' }, { '#', '.', '#' } };
Output: 2
1 3
Approach
Java
public class Areas {private static int rows = 0;private static int cols = 0;public static void main(String[] args) {rows = 3;cols = 3;char[][] grid = { { '#', '#', '.' }, { '.', '.', '#' }, { '#', '.', '#' } };dfs(grid);}private static void dfs(char[][] grid) {int count = 0;StringBuilder builder = new StringBuilder();for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {if (grid[i][j] == '.') {count++;builder.append(helper(grid, i, j)).append(" ");}}}System.out.println(count);System.out.println(builder.toString().trim());}private static int helper(char[][] grid, int i, int j) {if (i < 0 || i >= rows)return 0;if (j < 0 || j >= cols)return 0;if (grid[i][j] == '#')return 0;grid[i][j] = '#';int area = 1;area += helper(grid, i + 1, j);area += helper(grid, i - 1, j);area += helper(grid, i, j - 1);area += helper(grid, i, j + 1);return area;}}
No comments:
Post a Comment