Islands (LeetCode200)

Subject description:

Given a two-dimensional grid by a '1' (land) and '0' (water) composition, the number of islands is calculated. An island surrounded by water, and it is through the horizontal or vertical direction is connected to each adjacent land. You can assume that the water surrounding the four sides of the grid are.

Example 1:

Enter:
11110
11010
11000
00000

Output: 1


Example 2:

Enter:
11000
11000
00100
00011

Output: 3

Problem-solving ideas:

For the matrix, traversal, if one is to position 1, the start of a "infection" process, that is, starting from the current position, put together into a 2 1 all become. "Infection" after the end of the process,

Continue to traverse the matrix, until the end. How many times have "infected" process, there are that many islands.

Achieve "infection" process. Suppose i row j column from position to position in order to go up and down about four "infection." Recursive function can be written.

 1 class Solution200 {
 2         public void infect(int[][] m,int i,int j,int N,int M) {
 3         if (i<0||i>=N||j<0||j>=M||m[i][j]!=1) {
 4             return;
 5         }
 6         m[i][j]=2;
 7         infect(m,i+1,j,N,M);
 8         infect(m,i-1,j,N,M);
 9         infect(m,i,j+1,N,M);
10         infect(m,i,j-1,N,M);
11     }
12     public int countIslands(int[][] m) {
13         if (m==null||m[0]==null) {
14             return 0;
15         }
16         int N=m.length;
17         int M=m[0].length;
18         int res=0;
19         for (int i=0; i<N; i++) {
20             for (int j=0; j<M; j++) {
21                 if (m[i][j]==1) {
22                     res++;
23                     infect(m,i,j,N,M);
24                 }
25             }
26         }
27         return res;
28     }
29     public static void main(String[] args) {
30         Solution200 s=new Solution200();
31         int[][] m={{1,0,1,1},{1,0,1,1},{0,0,0,0},{1,0,1,0}};
32         int result=s.countIslands(m);
33         System.out.println(result);
34     }
35 }

Time complexity is O (N × M)

 

 

 

Guess you like

Origin www.cnblogs.com/hengzhezou/p/11037329.html