SHARE
TWEET

Untitled

a guest Sep 15th, 2019 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Solution {
  2.     public int numIslands(char[][] grid) {
  3.         if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
  4.         boolean[][] visited = new boolean[grid.length][grid[0].length];
  5.         int res = 0;
  6.         for (int i = 0; i < grid.length; ++i) {
  7.             for (int j = 0; j < grid[0].length; ++j) {
  8.                 if (grid[i][j] == '1' && !visited[i][j]) {
  9.                     ++res;
  10.                     dfs(grid, visited, i, j);
  11.                 }
  12.             }
  13.         }
  14.         return res;
  15.     }
  16.     public void dfs(char[][] grid, boolean[][] visited, int i, int j) {
  17.         if (i >= 0 && j >=0 && i < grid.length && j < grid[0].length && !visited[i][j] && grid[i][j] == '1') {
  18.             visited[i][j] = true;
  19.             dfs(grid, visited, i + 1, j);
  20.             dfs(grid, visited, i - 1, j);
  21.             dfs(grid, visited, i, j + 1);
  22.             dfs(grid, visited, i, j - 1);
  23.         }
  24.     }
  25. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top