LeetCode solutions by tgic

Number of Islands

https://leetcode.com/problems/number-of-islands

Last Update 2015-04-08 07:07:58 +0000 View on Github

Source code Read on Github

 1 public class Solution {
 2 
 3     boolean allowed(int x, int y, final int mx, final int my, char[][] grid, boolean[][] visited){
 4         return (x < mx) && (x >= 0)
 5             && (y < my) && (y >= 0)
 6             && (grid[x][y] == '1')
 7             && (!visited[x][y]);
 8     }
 9 
10     void travel(int x, int y, final int mx, final int my, char[][] grid, boolean[][] visited){
11 
12         // x - 1, y
13         // x + 1, y
14         // x, y - 1
15         // x, y + 1
16 
17         visited[x][y] = true;
18 
19         for(int[] xy: new int[][]{ {x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1} }){
20 
21             int _x = xy[0];
22             int _y = xy[1];
23 
24             if(allowed(_x, _y, mx, my, grid, visited)){
25                 travel(_x, _y, mx, my, grid, visited);
26             }
27         }
28 
29     }
30 
31     public int numIslands(char[][] grid) {
32 
33         final int mx = grid.length;
34         if(mx == 0) return 0;
35         final int my = grid[0].length;
36 
37         int count = 0;
38         boolean[][] visited = new boolean[mx][my];
39 
40         for(int x = 0; x < mx; x++){
41             for(int y = 0; y < my; y++){
42                 if(allowed(x, y, mx, my, grid, visited)){
43 
44                     travel(x, y, mx, my, grid, visited);
45 
46                     count++;
47                 }
48             }
49         }
50 
51         return count;
52     }
53 }
comments powered by Disqus

LeetCode solutions by tgic

  • LeetCode solutions by tgic
  • [email protected]
  • Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
  • tg123
  • tg123/leetcode

LeetCode java solutions by tgic