☑️ 문제: 무인도 여행
https://school.programmers.co.kr/learn/courses/30/lessons/154540
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
☑️ Code
import java.util.*;
class Solution {
public int[] solution(String[] maps) {
int row = maps.length;
int col = maps[0].length();
// String[] maps -> int[][] nums
int[][] nums = new int[row][col];
for (int i = 0; i < row; i++) {
String line = maps[i];
for (int j = 0; j < col; j++) {
char ch = line.charAt(j);
if (ch == 'X') {
nums[i][j] = 0;
} else {
nums[i][j] = ch - '0';
}
}
}
ArrayList<Integer> answer = new ArrayList<Integer>();
boolean[][] visited = new boolean[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (nums[i][j] > 0 && !visited[i][j]) {
answer.add(bfs(nums, visited, i, j));
}
}
}
int[] array = {-1};
if (answer.size() > 0) {
array = answer.stream().mapToInt(i -> i).toArray();
Arrays.sort(array);
}
return array;
}
int bfs(int[][] nums, boolean[][] visited, int startRow, int startCol) {
int[] dRow = { 0, 0, 1, -1 };
int[] dCol = { 1, -1, 0, 0 };
int maxRow = nums.length;
int maxCol = nums[0].length;
Queue<Integer> queueRow = new LinkedList<>();
Queue<Integer> queueCol = new LinkedList<>();
visited[startRow][startCol] = true;
queueRow.offer(startRow);
queueCol.offer(startCol);
int count = nums[startRow][startCol];
while(!queueRow.isEmpty()) {
int row = queueRow.poll();
int col = queueCol.poll();
for(int i = 0; i < 4; i++) {
int nRow = row + dRow[i];
int nCol = col + dCol[i];
if (isBound(maxRow, maxCol, nRow, nCol) && nums[nRow][nCol] > 0 && !visited[nRow][nCol]) {
visited[nRow][nCol] = true;
queueRow.offer(nRow);
queueCol.offer(nCol);
count += nums[nRow][nCol];
}
}
}
return count;
}
boolean isBound(int maxR, int maxC, int r, int c) {
return r >= 0 && c >= 0 && r < maxR && c < maxC;
}
}
// 'X' : 바다, 무인도 아님
// 1에서 9 사이의 자연수 : 무인도
'TIL (Today I Learned)' 카테고리의 다른 글
99클럽 코테 스터디 34일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.24 |
---|---|
99클럽 코테 스터디 33일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.24 |
99클럽 코테 스터디 31일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.21 |
99클럽 코테 스터디 30일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.21 |
99클럽 코테 스터디 29일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.19 |