力扣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]);
	}
}
相关推荐
8Qi813 小时前
回文子串(Palindromic Substrings)—— 题解
算法·leetcode·职场和发展·动态规划
小欣加油18 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
兰令水1 天前
leecodecode【区间DP+树形DP】【2026.6.10打卡-java版本】
java·算法·leetcode
8Qi81 天前
LeetCode 4:寻找两个正序数组的中位数 —— 二分查找法
java·算法·leetcode·职场和发展·二分查找
8Qi81 天前
LeetCode 32:最长有效括号 —— 栈 + 标记法 题解
java·数据结构·算法·leetcode·职场和发展··括号匹配
Tairitsu_H1 天前
[LC优选算法#3] 滑动窗口 | 将x减到0的最⼩操作数 | ⽔果成篮 | 字⺟异位词
c++·算法·leetcode·滑动窗口
洛水水1 天前
【力扣100题】76.搜索插入位置
数据结构·算法·leetcode
wabs6661 天前
关于动态规划【力扣343.整数拆分的递推公式怎么理解?】
算法·leetcode·动态规划
承渊政道1 天前
【MySQL数据库学习】MySQL基本查询(下)
数据库·学习·mysql·leetcode·bash·数据库开发·数据库系统
洛水水1 天前
【力扣100题】78.在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode