力扣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]);
	}
}
相关推荐
Navigator_Z5 小时前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode
驭渊的小故事9 小时前
LeetCode 33:搜索旋转排序数组——从二分查找到旋转数组的区间判定
算法·leetcode·职场和发展
郝学胜-神的一滴1 天前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger1 天前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
Navigator_Z1 天前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
Pniubi3 天前
力扣2 . 两数相加
算法·leetcode·职场和发展
文丑颜不良啊3 天前
LeetCode3401~3420题目解析
java·leetcode
文丑颜不良啊3 天前
LeetCode3421~3440题目解析
java·leetcode
LK_074 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi4 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展