首页 > 其他 > 详细

LeetCode Number of Islands

时间:2015-10-17 09:26:15      阅读:158      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/number-of-islands/

若是碰到一个1, res++, 用DFS把与它相连的1 都换成0. 继续扫描,最后算出能有多少个 单独的 1.

AC Java:

 1 public class Solution {
 2     public int numIslands(char[][] grid) {
 3         if(grid == null || grid.length == 0 || grid[0].length == 0){
 4             return 0;
 5         }
 6         int res = 0;
 7         for(int i = 0; i<grid.length; i++){
 8             for(int j = 0; j<grid[0].length; j++){
 9                 if(grid[i][j] == ‘1‘){
10                     res++;
11                     replace(grid,i,j);
12                 }
13             }
14         }
15         return res;
16     }
17     private void replace(char[][] grid, int i, int j){
18         if(i<0 || i>=grid.length || j<0 || j>=grid[0].length || grid[i][j] != ‘1‘){
19             return;
20         }
21         grid[i][j] = ‘0‘;
22         replace(grid,i-1,j);
23         replace(grid,i+1,j);
24         replace(grid,i,j-1);
25         replace(grid,i,j+1);
26     }
27 }

 

LeetCode Number of Islands

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4886884.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!