A x B인 지도 안에서 0,0
좌표에서 시작하여 0,1
0,2
...
A,9
A,B
까지 순서대로 진행하면서 무인도를 찾을 경우 무인도를 찾은 좌표에서 상하좌우로 퍼저나가며 하나의 식량을 합한다
int island = 1;
String[] worldMaps;
int[][] sameIsland;
Map<Integer, Integer> islandFood = new HashMap<>();
public Queue<int[]> queue = new LinkedList<>();
public int[] solution(String[] maps) {
this.worldMaps = maps;
sameIsland = new int[worldMaps.length][worldMaps[0].length()];
for(int i = 0; i < worldMaps.length; i++) {
for (int j = 0; j < maps[i].length(); j++) {
if(worldMaps[i].charAt(j) != 'X' && sameIsland[i][j] == 0){
queue.add(new int[]{i,j});
while(queue.size() > 0){
int[] x = queue.poll();
if(sameIsland[x[0]][x[1]] == 0){
sameIsland[x[0]][x[1]] = island;
Integer orDefault = islandFood.getOrDefault(island, 0);
Integer value = Integer.valueOf(String.valueOf(worldMaps[x[0]].charAt(x[1])));
islandFood.put(island, orDefault + value);
checkUp(x[0],x[1]);
checkLeft(x[0],x[1]);
checkRight(x[0],x[1]);
checkBottom(x[0],x[1]);
}
}
island++;
}
}
}
int[] answer;
if(islandFood.isEmpty()) answer = new int[]{-1};
else answer = islandFood.values().stream().mapToInt(Integer::intValue).sorted().toArray();
return answer;
}
void checkBottom(int i, int j){
if(i >= worldMaps.length-1) return;
if(worldMaps[i+1].charAt(j) == 'X') return;
int sideIslandNumber = sameIsland[i+1][j];
if (sideIslandNumber == 0) queue.add(new int[]{i+1,j});
}
void checkUp(int i, int j){
if(i <= 0) return;
if(worldMaps[i-1].charAt(j) == 'X') return;
int sideIslandNumber = sameIsland[i-1][j];
if(sideIslandNumber == 0) queue.add(new int[]{i-1,j});
}
void checkLeft(int i, int j){
if(j <= 0) return;
if(worldMaps[i].charAt(j-1) == 'X') return;
int sideIslandNumber = sameIsland[i][j-1];
if(sideIslandNumber == 0) queue.add(new int[]{i,j-1});
}
void checkRight(int i, int j){
if(j >= worldMaps[0].length()-1) return;
if(worldMaps[i].charAt(j+1) == 'X') return;
int sideIslandNumber = sameIsland[i][j+1];
if(sideIslandNumber == 0) queue.add(new int[]{i,j+1});
}