Trzech Polaków w teamie?
JCHJava Community | Help. Code. Learn.
•Created by Trzech Polaków w teamie? on 10/30/2024 in #java-help
How to find the biggest island in the file
I have two-dimensional array of chars called map. Map contains three types of cell: x-land, u-river, o-sea. My task is to find the biggest island. Island is landmass connected in any of eight directions - up, top right, right... and surrounded by sea cells. There is a row that contains only sea tiles and can be interpreted as sealine that sea will not cross. Rivers do not exist on islands. I already made a method to find the longest river but i got stuck on finding the biggest isle, any advices?
the answear should be 19
public static int findLargestIsland(int x, int y) {
if (x < 0 x >= columnsAmount y < 0 y >= rowsAmount map[x][y] != 'x') { return 0; }
map[x][y] = '?';
int size = 1;
size += findLargestIsland(x - 1, y); size += findLargestIsland(x + 1, y); size += findLargestIsland(x, y - 1); size += findLargestIsland(x, y + 1); size += findLargestIsland(x - 1, y - 1); size += findLargestIsland(x - 1, y + 1); size += findLargestIsland(x + 1, y - 1); size += findLargestIsland(x + 1, y + 1);
return size; }
public static int findLargestIslandInMap() { int largestIsland = 0;
for (int i = 0; i < columnsAmount; i++) { for (int j = 0; j < rowsAmount; j++) { if (map[i][j] == 'x') { int currentIslandSize = findLargestIsland(i, j); largestIsland = Math.max(largestIsland, currentIslandSize); } } }
return largestIsland; }
if (x < 0 x >= columnsAmount y < 0 y >= rowsAmount map[x][y] != 'x') { return 0; }
map[x][y] = '?';
int size = 1;
size += findLargestIsland(x - 1, y); size += findLargestIsland(x + 1, y); size += findLargestIsland(x, y - 1); size += findLargestIsland(x, y + 1); size += findLargestIsland(x - 1, y - 1); size += findLargestIsland(x - 1, y + 1); size += findLargestIsland(x + 1, y - 1); size += findLargestIsland(x + 1, y + 1);
return size; }
public static int findLargestIslandInMap() { int largestIsland = 0;
for (int i = 0; i < columnsAmount; i++) { for (int j = 0; j < rowsAmount; j++) { if (map[i][j] == 'x') { int currentIslandSize = findLargestIsland(i, j); largestIsland = Math.max(largestIsland, currentIslandSize); } } }
return largestIsland; }
7 replies