題目描述:
給定一個由 '1'(陸地)和 '0'(水)組成的的二維網格,計算島嶼的數量。一個島被水包圍,並且它是通過水平方向或垂直方向上相鄰的陸地連接而成的。你可以假設網格的四個邊均被水包圍。
示例 1:
輸入:
11110
11010
11000
00000
輸出: 1
示例 2:
輸入:
11000
11000
00100
00011
輸出: 3
解題思路:
對於matrix,遍歷,如果來到一個是1的位置,開始一個“感染”過程,就是從當前位置出發,把連成一片的1全部變成2。“感染”過程結束之后,
繼續遍歷matrix,直到結束。有多少次“感染”過程,就有多少個島。
實現“感染”過程。假設從i行j列位置出發,向上下左右四個位置依次去“感染”。寫成遞歸函數即可。
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 }
時間復雜度為O(N×M)