Number of Islands

来源:互联网 发布:董成鹏抄袭知乎 编辑:程序博客网 时间:2024/05/17 05:15
DescriptionSubmissionsSolutions
  • Total Accepted: 96206
  • Total Submissions: 288576
  • Difficulty: Medium
  • Contributor: LeetCode

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No
Discuss Pick One 

Java  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
publicclass Solution {
publicint numIslands(char[][] grid) {
intres=0;
for(inti=0;i<grid.length;i++)
for(intj=0;j<grid[0].length;j++)
if(grid[i][j]=='1'){
res++;
bfs(grid,i,j);
}
returnres;
}
publicvoid bfs(char[][] grid,int x,int y){
LinkedList<int[]>que=newLinkedList<int[]>();
que.addLast(newint[]{x,y});
int[][]f={{1,0},{-1,0},{0,1},{0,-1}};
grid[x][y]='0';
while(!que.isEmpty()){
int[]cur=que.pollFirst();
for(int[]ff:f){
intr=cur[0]+ff[0];
intc=cur[1]+ff[1];
if(r>=0&&r<grid.length&&c>=0&&c<grid[0].length&&grid[r][c]=='1'){
grid[r][c]='0';
que.addLast(newint[]{r,c});
}
}
}
}
}
时间复杂度:O(N*M)
0 0