1+ package com .leetcode .arrays ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertEquals ;
4+
5+ /**
6+ * Level: Medium
7+ * Link: https://leetcode.com/problems/number-of-islands/
8+ * Description:
9+ * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water
10+ * and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid
11+ * are all surrounded by water.
12+ * <p>
13+ * Example 1:
14+ * Input:
15+ * 11110
16+ * 11010
17+ * 11000
18+ * 00000
19+ * Output: 1
20+ * <p>
21+ * Example 2:
22+ * Input:
23+ * 11000
24+ * 11000
25+ * 00100
26+ * 00011
27+ * Output: 3
28+ *
29+ * @author rampatra
30+ * @since 2019-08-07
31+ */
32+ public class NumberOfIslands {
33+
34+ /**
35+ * The idea is simple and straightforward. Once we encounter land ('1' in grid) we drown the island or change the
36+ * neighboring '1's to '0's. Therefore, the number of '1's we encounter, we can say that we have that many islands.
37+ * <p>
38+ * Time Complexity: O(n)
39+ * Space Complexity: O(n)
40+ * Runtime: <a href="https://leetcode.com/submissions/detail/249754904/">1 ms</a>.
41+ *
42+ * @param grid
43+ * @return
44+ */
45+ public static int numIslands (char [][] grid ) {
46+ int count = 0 ;
47+
48+ for (int i = 0 ; i < grid .length ; i ++) {
49+ for (int j = 0 ; j < grid [0 ].length ; j ++) {
50+ if (grid [i ][j ] == '1' ) {
51+ drownTheIsland (grid , i , j );
52+ count ++;
53+ }
54+ }
55+ }
56+
57+ return count ;
58+ }
59+
60+ private static void drownTheIsland (char [][] grid , int i , int j ) {
61+ if (i < 0 || j < 0 || i >= grid .length || j >= grid [0 ].length || grid [i ][j ] == '0' ) {
62+ return ;
63+ }
64+
65+ grid [i ][j ] = '0' ;
66+
67+ drownTheIsland (grid , i , j + 1 );
68+ drownTheIsland (grid , i , j - 1 );
69+ drownTheIsland (grid , i + 1 , j );
70+ drownTheIsland (grid , i - 1 , j );
71+ }
72+
73+ public static void main (String [] args ) {
74+ assertEquals (1 , numIslands (new char [][]{
75+ {'1' , '1' , '1' , '1' , '0' },
76+ {'1' , '1' , '0' , '1' , '0' },
77+ {'1' , '1' , '0' , '0' , '0' },
78+ {'0' , '0' , '0' , '0' , '0' }
79+ }));
80+
81+ assertEquals (2 , numIslands (new char [][]{
82+ {'1' , '1' , '1' , '1' , '0' },
83+ {'1' , '1' , '0' , '1' , '0' },
84+ {'1' , '1' , '0' , '0' , '0' },
85+ {'0' , '0' , '0' , '1' , '0' }
86+ }));
87+
88+ assertEquals (1 , numIslands (new char [][]{
89+ {'1' , '1' , '1' , '1' , '1' },
90+ {'1' , '1' , '1' , '1' , '1' },
91+ {'1' , '1' , '1' , '1' , '1' },
92+ {'1' , '1' , '1' , '1' , '1' }
93+ }));
94+
95+ assertEquals (1 , numIslands (new char [][]{
96+ {'1' }
97+ }));
98+
99+ assertEquals (0 , numIslands (new char [][]{
100+ {'0' }
101+ }));
102+
103+ assertEquals (0 , numIslands (new char [][]{
104+ {}
105+ }));
106+ }
107+ }
0 commit comments