
| class Solution { |
| public static int MAXN = 90001; |
| |
| public static int[] f = new int[MAXN]; |
| |
| public static int n = 0; |
| |
| public static int union_count = 0; |
| |
| public static boolean isSameSet(int i, int j) { |
| return find(i) == find(j); |
| } |
| |
| public static int find(int i) { |
| |
| if (f[i] != i) { |
| f[i] = find(f[i]); |
| } |
| return f[i]; |
| } |
| |
| public static void union(int i, int j) { |
| int f_i = find(i); |
| int f_j = find(j); |
| if (f_i != f_j) { |
| f[f_i] = f_j; |
| union_count++; |
| } |
| } |
| |
| public static void build(int m, int nn) { |
| for (int i = 0; i < m * nn; i++) { |
| f[i] = i; |
| } |
| n = m; |
| union_count = 0; |
| } |
| |
| public static int index(int i, int j) { |
| return j * n + i; |
| } |
| |
| public static void main(String[] args) { |
| new Solution().numIslands(new char[][] { { '1', '0', '1', '1', '0', '1', '1' } }); |
| } |
| |
| public int numIslands(char[][] grid) { |
| |
| |
| int m = grid.length; |
| int nn = grid[0].length; |
| build(m, nn); |
| int count_1 = 0; |
| for (int i = 0; i < m; i++) { |
| for (int j = 0; j < nn; j++) { |
| |
| if (grid[i][j] == '0') { |
| continue; |
| } |
| count_1++; |
| int cur_index = index(i, j); |
| |
| if (j + 1 < nn && grid[i][j + 1] == '1') { |
| int right_index = index(i, j + 1); |
| union(cur_index, right_index); |
| } |
| |
| if (i + 1 < m && grid[i + 1][j] == '1') { |
| int down_index = index(i + 1, j); |
| union(cur_index, down_index); |
| } |
| } |
| } |
| return count_1 - union_count; |
| |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统