最近整理了一下常见的岛屿问题,在力扣上测试了一行,性能很差,但是终归还能是跑起来了,暂时没有时间去优化它了,只能等以后再说了,
下面简单介绍一下岛屿问题:
题目链接如下
https://leetcode-cn.com/problems/number-of-islands/
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。 此外,你可以假设该网格的四条边均被水包围。
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
从上面的题目描述中可以得到一下思路
从第一个点开始遍历,找到岛屿点就要开始像四个方向蔓延,并将蔓延到的岛屿加入到记录的集合中,直到该岛屿的蔓延结束。 然后开始下一个点开始遍历,第二次遍历时要跳过已经在集合中的点。针对以上思路,可以写出如下代码:
1 package island; 2 3 import java.util.Arrays; 4 import java.util.HashSet; 5 import java.util.Set; 6 7 public class IslandTest { 8 9 static Set<String> isLandSet = null; 10 11 public static void Traverse(char[][] arr,int i,int j) { 12 isLandSet.add(i+","+j); 13 14 //上 15 int a,b,c,d = 0; 16 if(( a = i-1)>-1) { 17 if(arr[a][j] =='1' && !isLandSet.contains((a)+","+j)) { 18 Traverse(arr, a, j); 19 } 20 } 21 22 23 //下 24 if(( b = i+1) < arr.length) { 25 if(arr[b][j] =='1' && !isLandSet.contains((b)+","+j)) { 26 Traverse(arr, b, j); 27 } 28 } 29 //左 30 if(( c = j-1) > -1) { 31 if(arr[i][c] =='1' && !isLandSet.contains((i)+","+c)) { 32 Traverse(arr, i, c); 33 } 34 } 35 //右 36 if(( d = j+1) < arr[i].length) { 37 if(arr[i][d] =='1' && !isLandSet.contains((i)+","+d)) { 38 Traverse(arr, i, d); 39 } 40 } 41 42 } 43 44 public static int getIslandCount(char[][] arr) { 45 46 //定义已经遍历过的岛屿数量 47 isLandSet = new HashSet<String>(); 48 int count = 0; 49 for(int i = 0;i<arr.length;i++) 50 { 51 for(int j = 0 ;j<arr[i].length;j++) { 52 if(arr[i][j]=='1' && !isLandSet.contains(i+","+j) ) 53 { 54 count++; 55 Traverse(arr,i,j); 56 } 57 } 58 } 59 60 return count; 61 } 62 63 64 65 66 public static void main(String[] args) { 67 68 char[][] islands = new char[][] {{'1','0','0'},{'0','1','1'},{'1','0','0'}}; 69 // System.out.println(Arrays.toString(islands[0])); 70 System.out.println(getIslandCount(islands)); 71 72 } 73 }
就简单做一个记录吧。