Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 백준
- 트리맵
- 프로젝트
- 그래프탐색
- 구현
- flyway
- 트리셋
- findById
- BFS
- 컴퓨터구조
- 외래키제약조건위반
- DB replication
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- 산업은행it
- CS
- 파이널프로젝트
- SpringBatch
- CPU스케줄링
- JPA
- Spring JPA
- 산업은행청년인턴
- fatch
- 코테
- 운영체제
- 폰켓몬
- 스케일아웃
- 2178
- 임베디드타입
- 프로그래머스
- 해시
Archives
- Today
- Total
나 JAVA 봐라
[코드트리] 상한 귤 본문
https://www.codetree.ai/ko/trails/personalized/curated-cards/test-oranges-have-gone-bad/description
Codetree: Master Coding Interviews - Data Structures & Algorithms
Master algorithms, ace tech interviews, and elevate your coding skills with Codetree's systematic curriculum and expert-crafted problem sets.
www.codetree.ai
BFS 문제긴 한데, 시간을 고려해야하는 조건이 추가되어서 살짝 고민함.
처음에 for문으로 0초 ~ 끝까지 반복하면서 BFS 돌려야하나? 생각했는데... 멍청한 생각이었음
그냥 Pair 클래스 변수에 time 정보도 넣으면 쉽게 해결될 문제였음
BFS 자체가 Queue 사용하니까, 시간 순서대로 알아서 처리해줌
import java.util.*;
class Pair{
int x,y,time;
public Pair(int x, int y, int time){
this.x = x;
this.y = y;
this.time = time;
}
}
public class Main {
static int n,k;
static int grid[][];
static int result[][];
static boolean visit[][];
static Queue<Pair> q = new LinkedList<>();
static int dx[] = {0,0,-1,1};
static int dy[] = {-1,1,0,0};
public static boolean inRange(int x, int y){
return x >= 0 && x < n && y >= 0 && y < n;
}
public static void bfs(){
while(!q.isEmpty()){
Pair p = q.poll();
for (int i = 0; i < 4; i++){
int nx = p.x + dx[i];
int ny = p.y + dy[i];
if (inRange(nx,ny) && !visit[nx][ny] && (grid[nx][ny] == 1)){
result[nx][ny] = p.time+1;
visit[nx][ny] = true;
q.add(new Pair(nx,ny,p.time+1));
}
}
}
}
public static void main(String[] args) {
// 1. 변수 초기화 과정
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
grid = new int[n][n];
result = new int[n][n];
visit = new boolean[n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
int value = sc.nextInt();
grid[i][j] = value;
if(value == 0){
visit[i][j] = true;
result[i][j] = -1;
}
else if(value == 2){
q.add(new Pair(i,j,0));
visit[i][j] = true; //result는 초기화되면 자동으로 0이니까 안해도 ㅇㅋ
}
}
}
// 2. 탐색 시작
bfs();
// 3. 예외 처리 (끝까지 상하지 않는 귤)
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (!visit[i][j]) {
result[i][j] = -2;
}
}
}
for (int i = 0; i < n; i++){
for (int j =0; j < n; j++){
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
'코딩테스트 > 그래프 탐색' 카테고리의 다른 글
[백준] 1987번 알파벳 (비트마스크로 풀기) (2) | 2025.04.24 |
---|---|
[코드트리] 마을 구분하기 문제 (2) | 2025.02.28 |
[프로그래머스] 여행경로 (0) | 2024.07.17 |
[프로그래머스] 전력망을 둘로 나누기 (4) | 2024.07.15 |
[프로그래머스] 피로도 (0) | 2024.07.15 |