力扣hot100 岛屿数量 dfs 图论

Problem: 200. 岛屿数量

文章目录

思路

复杂度

时间复杂度: O ( n ) O(n) O(n)

空间复杂度: O ( 1 ) O(1) O(1)

Code

Java 复制代码
class Solution {
	int n, m;

	public int numIslands(char[][] grid)
	{
		n = grid.length;
		if (n == 0)
			return 0;
		m = grid[0].length;
		int ans = 0;
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++)
				if (grid[i][j] == '1')
				{
					dfs(grid, i, j);
					ans++;
				}
		return ans;
	}

	private void dfs(char[][] g, int x, int y)
	{
		if (x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '0')
			return;
		g[x][y] = '0';
		int[] dx = { 0, 1, 0, -1 };
		int[] dy = { 1, 0, -1, 0 };
		for (int i = 0; i < 4; i++)
			dfs(g, x + dx[i], y + dy[i]);
	}
}
相关推荐
琢磨先生David3 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll3 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐3 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶3 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
独自破碎E3 天前
【DFS】BISHI76 迷宫寻路
算法·深度优先
代码无bug抓狂人3 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
im_AMBER3 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了3 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
码农幻想梦3 天前
3472. 八皇后(北京大学考研机试题目)
考研·算法·深度优先