DFS

↘锁芯ラ 提交于 2020-02-05 05:15:34

在LeetCode刷题时碰到一个DFS的问题 一开始是觉得用DFS解决的 =-= 对DFS不熟悉(太久没用了),用自己的方法 实在太麻烦(主要是为啥别人参数传递一个数组 可以改变数组内元素的值 我传个数组进去 咋变不鸟 以后的看看参数传递方面的东西),用DFS简单明了
题目如下 :
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:

Input:
11110
11010
11000
00000

Output: 1
Example 2:

Input:
11000
11000
00100
00011

Output: 3

解题思路 :因为islands是被0包围起来的,所以所有垂直和水平连着的‘1’ 就是一个 islands,这个就是典型的DFS算法思想 根据一个点 深度优先遍历它的上下左右所有类似的节点即可 。 然后把它遍历到的节点设置为‘0’ 一次遍历后 islands的值++ .

具体代码如下 :

public static int numIslands(char[][] grid) {
    	int islands = 0;
    	for(int i=0;i<grid.length;i++){
    		for(int j=0;j<grid[i].length;j++){
    			if(grid[i][j] == '1'){
    				islands ++;
    				dfs(i,j,grid);
    			}
    		}
    	}
    	return islands;
    }
    
    public static void dfs(int r,int c,char[][] grid){
    	if(!(r<grid.length && r>=0 && c<grid[r].length&&c>=0&&grid[r][c] == '1')){
    		return ;
    	}
    	grid[r][c] = '0';
    	dfs(r+1,c,grid);
    	dfs(r-1,c,grid);
    	dfs(r,c+1,grid);
    	dfs(r,c-1,grid);
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!