前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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
这个题目最优的解法应该是O(n^2)我的解法接近O(n^2)。 Your runtime beats 28.20% of java submissions.public class Solution {
public int numIslands(char[][] grid) {
if(grid.length == 0) return 0;
int[][] flag = new int[grid.length][grid[0].length];
int count = 0;
for(int i = 0; i < grid.length; i ++)
for(int j = 0; j < grid[i].length; j ++){
if(grid[i][j] == '1' && flag[i][j] == 0){
findLand(grid,flag,i,j);
count++;
}
}
return count;
}
public void findLand(char[][] grid, int[][] flag,int i, int j){
if(i < 0 || i >= grid.length) return;
if(j < 0 || j >= grid[0].length) return;
if(grid[i][j] == '1' && flag[i][j] == 0){
flag[i][j] = 1;
if(i < grid.length - 1 && grid[i+1][j] == '1') findLand(grid,flag,i+1,j);
if(j < grid[0].length - 1 && grid[i][j+1] == '1') findLand(grid,flag,i,j+1);
if(i > 0 && grid[i-1][j] == '1') findLand(grid,flag,i-1,j);
if(j > 0 && grid[i][j-1] == '1') findLand(grid,flag,i,j-1);
}
}
}