https://school.programmers.co.kr/learn/courses/30/lessons/250136
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
bfs로 풀면 될 것이다.
import java.util.*;
class Solution {
public int [] dx = {0,0,-1,1};
public int [] dy = {1,-1,0,0};
public int solution(int[][] land) {
int answer = 0;
for(int i = 0; i < land[0].length; i++) {
answer = Math.max(bfs(i, land), answer);
}
return answer;
}
private int bfs(int m, int[][] land) {
int result = 0;
boolean[][] visited = new boolean[land.length][land[0].length];
Queue<int[]> q = new LinkedList<>();
for(int i = 0; i < land.length; i++) {
if(visited[i][m]) continue;
if(land[i][m] == 1) {
visited[i][m] = true;
q.offer(new int[]{i , m});
}
while(!q.isEmpty()) {
int[] currQ = q.poll();
int currX = currQ[0];
int currY = currQ[1];
result++;
for(int j = 0; j < 4; j++) {
int x = currX + dx[j];
int y = currY + dy[j];
if(x >= 0 && y >= 0 && x < land.length && y < land[0].length && !visited[x][y] && land[x][y] == 1) {
visited[x][y] = true;
q.offer(new int[]{x, y});
}
}
}
}
return result;
}
}
효율성 테스트에서 시간 초과가 났다.
이미 파악된 석유덩어리의 크기를 따로 저장해서 그 석유 덩어리를 만난다면 순회하지 않고 계산해주면 될 것 같다.
(귀찮아서 이만..)
'알고리즘 > Lv2. 프로그래머스' 카테고리의 다른 글
[프로그래머스] 요격 시스템 -JAVA (0) | 2024.09.10 |
---|---|
[프로그래머스]디펜스게임 -JAVA (2) | 2024.09.04 |
[프로그래머스]무인도 여행 -JAVA (4) | 2024.09.04 |
[프로그래머스]귤 고르기 -JAVA (0) | 2024.08.21 |
[프로그래머스] 점프와 순간 이동 -JAVA (0) | 2024.08.20 |