力扣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]);
	}
}
相关推荐
刃神太酷啦17 小时前
聚焦 string:C++ 文本处理的核心利器--《Hello C++ Wrold!》(10)--(C/C++)
java·c语言·c++·qt·算法·leetcode·github
哎写bug的程序员2 天前
leetcode复盘(1)
算法·leetcode·职场和发展
qq_534452522 天前
【算法 day02】LeetCode 209.长度最小的子数组 | 59.螺旋矩阵II
java·算法·leetcode·职场和发展
dying_man2 天前
LeetCode--31.下一个排列
算法·leetcode
IC 见路不走2 天前
LeetCode 第75题:颜色分类
数据结构·算法·leetcode
Navigator_Z2 天前
LeetCode //C - 757. Set Intersection Size At Least Two
c语言·算法·leetcode
GalaxyPokemon2 天前
LeetCode - 704. 二分查找
数据结构·算法·leetcode
liuqun03192 天前
开心灿烂go开发面试题
算法·leetcode·golang
এ᭄画画的北北2 天前
力扣-279.完全平方数
数据结构·算法·leetcode
GalaxyPokemon2 天前
LeetCode - LCR 173. 点名
算法·leetcode·职场和发展