描述 给一个01矩阵,求不同的岛屿的个数。 0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。 样例 在矩阵: [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1] ] 中有 3 个岛。 代码 GitHub 的源代码,请访问下面的链接: https://github.com/cwiki-us/java-tutorial/blob/master/src/test/java/com/ossez/lang/tutorial/tests/lintcode/LintCode0433NumIslandsTest.java package com.ossez.lang.tutorial.tests.lintcode; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * 433 * <ul> * <li>@see <a href= * "https://www.cwiki.us/display/ITCLASSIFICATION/Number+of+Islands">https://www.cwiki.us/display/ITCLASSIFICATION/Number+of+Islands</a> * <li>@see<a href="https://www.lintcode.com/problem/number-of-islands/">https://www.lintcode.com/problem/number-of-islands/</a> * </ul> * </p> * * @author YuCheng * */ public class LintCode0433NumIslandsTest { private final static Logger logger = LoggerFactory.getLogger(LintCode0433NumIslandsTest.class); /** * */ @Test public void testMain() { logger.debug("BEGIN"); // INIT GRID boolean[][] grid = { { true, true, false, false, false }, { false, true, false, false, true }, { false, false, false, true, true }, { false, false, false, false, false }, { false, false, false, false, true } }; // NULL CHECK if (grid.length == 0 || grid[0].length == 0) { System.out.println("NULL"); // return 0; } // GET SIZE int n = grid.length; int m = grid[0].length; // ARRAY FOR VISITED LOG boolean[][] visited = new boolean[n][m]; int count = 0; // LOOP FOR GRID for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] && !visited[i][j]) { numIslandsDFS(grid, visited, i, j); count++; } } } System.out.println(count); } /** * * @param grid * @param visited * @param x * @param y */ public void numIslandsDFS(boolean[][] grid, boolean[][] visited, int x, int y) { if (x < 0 || x >= grid.length) { return; } if (y < 0 || y >=…