https://school.programmers.co.kr/learn/courses/30/lessons/154540
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
import java.util.*;
class Solution {
public int[] solution(String[] maps) {
int[] answer = {};
int n = maps.length;
int m = maps[0].length();
boolean[][] visited = new boolean[n][m];
List<Integer> result = new LinkedList<>();
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < m ; j++){
if(maps[i].charAt(j) != BLOCK && !visited[i][j]){
int cnt = cal(i,j,visited,n,m,maps);
result.add(cnt);
}
}
}
Collections.sort(result);
if(result.size() == 0){
answer = new int[]{-1};
}else{
answer = new int[result.size()];
for(int i = 0 ; i < result.size() ; i++){
answer[i] = result.get(i);
}
}
return answer;
}
private static final char BLOCK = 'X';
private static final int[] DY = {-1,0,1,0};
private static final int[] DX = {0,1,0,-1};
private static int cal(int y,int x,boolean[][] visited,int n,int m,String[] map){
Queue<int[]> q = new LinkedList<>();
q.offer(new int[]{y,x});
visited[y][x] = true;
int cnt = map[y].charAt(x) - '0';
while(!q.isEmpty()){
int[] now = q.poll();
for(int i = 0 ; i < 4 ; i++){
int ny = now[0] + DY[i];
int nx = now[1] + DX[i];
if(ny >= 0 && nx >= 0 && nx < m && ny < n && !visited[ny][nx]
&& map[ny].charAt(nx) != BLOCK){
q.offer(new int[] {ny,nx});
visited[ny][nx] = true;
cnt += map[ny].charAt(nx) - '0';
}
}
}
return cnt;
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 두 수의 합 (JAVA) (0) | 2023.03.23 |
---|---|
백준 25044번 에어컨 (JAVA) (0) | 2023.03.22 |
프로그래머스 택배상자 (JAVA) (0) | 2023.03.20 |
프로그래머스 문자열 정렬하기 (JAVA) (0) | 2023.03.19 |
프로그래머스 중앙값 구하기 (JAVA) (0) | 2023.03.18 |