Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- int[][] grid;
- int rows;
- int cols;
- int[][] dirs = new int[][] { {-1, 0}, {0, 1}, {1, 0}, {0, -1} };
- public int closedIsland(int[][] grid) {
- this.grid = grid;
- this.rows = grid.length;
- this.cols = grid[0].length;
- for (int r = 0; r < rows; r++) {
- for (int c = 0; c < cols; c++) {
- // if cell is zero and is at edge, mark it invalid
- if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {
- fill(r, c);
- }
- }
- }
- // count number of islands
- int count = 0;
- for (int r = 0; r < rows; r++) {
- for (int c = 0; c < cols; c++) {
- if (grid[r][c] == 0) {
- count++;
- fill(r, c);
- }
- }
- }
- return count;
- }
- void fill(int r, int c) {
- if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] != 0) {
- return;
- }
- grid[r][c] = 1;
- for (int[] dir : dirs) {
- int rr = r + dir[0];
- int cc = c + dir[1];
- fill(rr, cc);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement