public class NumContinents { public static void main(String[] args) { int[][] map = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0 }, { 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0 }, { 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0 }, { 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0 }, { 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0 }, { 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0 }, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0 }, { 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 } }; System.out.println(getNumContinents(map)); } public static int getNumContinents(int[][] map) { if (map == null) { return 0; } int rows = map.length; if (rows == 0) { return 0; } int cols = map[0].length; if (cols == 0) { return 0; } boolean[][] visited = new boolean[rows][cols]; int numContinents = 0; for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { boolean isContinent = traverse(map, visited, row, col); if (isContinent) { ++numContinents; } } } return numContinents; } private static boolean traverse(int[][] map, boolean[][] visited, int row, int col) { int rows = map.length; int cols = map[0].length; if (row < 0 || row >= rows || col < 0 || col >= cols || visited[row][col] || map[row][col] == 0) { return false; } visited[row][col] = true; traverse(map, visited, row - 1, col); traverse(map, visited, row + 1, col); traverse(map, visited, row, col + 1); traverse(map, visited, row, col - 1); return true; } }