programmers_무인도 여행_java
2023. 3. 30. 12:20ㆍAlgorithm/Programmers
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/154540
import java.util.*;
class Solution {
private static int[][] delta = {{1,0}, {-1,0}, {0, 1}, {0, -1}};
public int[] solution(String[] maps) {
int[] answer = {-1};
int width = maps[0].length();
int height = maps.length;
boolean[][] visited = new boolean[height][width];
StringBuilder sb = new StringBuilder();
boolean flag = false;
for(int i =0; i<height; i++){
for(int j = 0; j<width; j++){
if(!visited[i][j] && maps[i].charAt(j) != 'X'){
flag = true;
sb.append(bfs(maps, i, j, visited, width, height)).append(" ");
}
}
}
if(flag){
String[] ansArr = sb.toString().split(" ");
answer = Arrays.stream(ansArr).mapToInt(Integer::parseInt).toArray();
Arrays.sort(answer);
System.out.println(answer);
}
return answer;
}
private int bfs(String[] maps, int y, int x, boolean[][] visited, int width, int height){
Queue<Point> queue = new LinkedList<>();
queue.offer(new Point(y, x, maps[y].charAt(x) - '0'));
int days = 0;
while(!queue.isEmpty()){
Point now = queue.poll();
if(visited[now.y][now.x] ) continue;
visited[now.y][now.x] = true;
days+= now.food;
for(int i = 0; i<4; i++){
int nexty = now.y + delta[i][0];
int nextx = now.x + delta[i][1];
if(0<= nexty && nexty <height && 0<= nextx && nextx <width && !visited[nexty][nextx] && maps[nexty].charAt(nextx) != 'X'){
queue.offer(new Point(nexty, nextx, maps[nexty].charAt(nextx) - '0'));
}
}
}
return days;
}
private class Point{
int y, x, food;
public Point(int y, int x, int food){
this.y = y;
this.x = x;
this.food = food;
}
}
}
'Algorithm > Programmers' 카테고리의 다른 글
programmers_이진 변환 반복하기_java (0) | 2023.04.01 |
---|---|
programmers_디펜스 게임_java (0) | 2023.04.01 |
programmers_미로 탈출_java (0) | 2023.03.28 |
programmers_광물 캐기_java (0) | 2023.03.23 |
programmers_영어 끝말잇기_java (0) | 2023.03.22 |