문제
https://school.programmers.co.kr/learn/courses/30/lessons/154540
코드
import java.util.*;
class Solution {
char board[][];
boolean visited[][];
List<Integer> answer = new ArrayList<>();
int dx [] = {0, -1, 0, 1};
int dy [] = {-1, 0, 1, 0};
public List<Integer> solution(String[] maps) {
board = new char[maps.length][maps[0].length()];
visited = new boolean[maps.length][maps[0].length()];
for(int i=0;i<maps.length;i++){
for(int j=0;j<maps[0].length();j++){
board[i][j] = maps[i].charAt(j);
}
}
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]!='X'&&!visited[i][j]){
bfs(i, j);
}
}
}
Collections.sort(answer);
if(answer.size() == 0) answer.add(-1);
return answer;
}
void bfs(int x, int y){
Queue<int []> que = new LinkedList<>();
visited[x][y] = true;
que.add(new int []{x, y});
int count = board[x][y] - '0';
while(!que.isEmpty()){
int cur [] = que.poll();
for(int i=0;i<4;i++){
int nx = cur[0] + dx[i];
int ny = cur[1] + dy[i];
if(nx < 0 || ny < 0 || nx >= board.length || ny >= board[0].length)
continue;
if(visited[nx][ny] || board[nx][ny] == 'X') continue;
visited[nx][ny] = true;
que.add(new int[]{nx, ny});
count += board[nx][ny] - '0';
}
}
answer.add(count);
}
}