티스토리 뷰
문제 링크 : https://www.acmicpc.net/problem/14940
🍊해결방법
- arr2 배열에 문제에서 주어진 arr 배열 중 2와 0을 0으로 저장하고 나머지는 -1로 저장
- 2인 좌표에서 시작해서 -1인 아직 도착하지 않은 지역으로 이동
- 이동하면서 전의 거리 d + 1을 저장
- 중복방문의 우려는 이미 -1인 곳만 방문하기 때문에 고려 X
- print로 출력하게되면 시간이 오래 걸리니 StringBuilder 활용
😀풀이
import java.io.*;
import java.util.*;
public class Main {
static class Node{
int x, y, d;
public Node(int x, int y, int d){
this.x = x;
this.y = y;
this.d = d;
}
}
static int N;
static int M;
static int[][] arr;
static int[][] arr2;
static Queue<Node> q;
static int[] dx = {-1, +1, 0, 0};
static int[] dy = {0, 0, -1, +1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
arr = new int[N][M];
arr2 = new int[N][M];
int sx = 0;
int sy = 0;
for(int i=0; i<N; i++){
st = new StringTokenizer(br.readLine());
for(int j=0; j<M; j++){
arr[i][j] = Integer.parseInt(st.nextToken());
if (arr[i][j] == 2){
sx = i;
sy = j;
arr2[i][j] = 0;
continue;
}
if (arr[i][j] == 0){
arr2[i][j] = 0;
continue;
}
arr2[i][j] = -1;
}
}
q = new LinkedList<>();
bfs(sx, sy);
StringBuilder sb = new StringBuilder();
for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
sb.append(arr2[i][j]+" ");
}
sb.append("\n");
}
System.out.println(sb);
}
static void bfs(int x, int y){
q.add(new Node(x, y, 0));
while(!q.isEmpty()){
Node p = q.poll();
for(int i=0; i<4; i++){
int nx = p.x + dx[i];
int ny = p.y + dy[i];
if (nx >= 0 && nx < N && ny >= 0 && ny < M){
if (arr2[nx][ny] == -1){
q.add(new Node(nx, ny, p.d+1));
arr2[nx][ny] = p.d + 1;
}
}
}
}
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 11058 크리보드 - DP (0) | 2024.10.25 |
---|---|
[백준] 3226 전화요금 - 구현 (0) | 2024.10.24 |
[백준] 12100 2048(easy) - 구현 (0) | 2024.10.23 |
[백준] 2637 장난감 조립 - 위상정렬 (1) | 2024.10.22 |
[백준] 1450 냅색문제 - 이진탐색 (0) | 2024.10.22 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 위상정렬
- 바텀업
- 스프링부트3 java 버전오류
- 이진탐색
- leetcode 1552
- 백준
- 티스토리챌린지
- 조합
- 탑다운
- 백준 경사로
- 스프링부트3
- 누적합
- 백준 14890 자바
- 스프링부트3 자바 버전
- 1482
- 탑다운dp
- 백준 경사로 자바
- 슬라이딩윈도우
- 투포인터
- 구현
- 스프링부트3 자바 17 오류
- 유니온파인드
- dp
- 백준 14890
- 오블완
- 백준 14890 경사로
- #스프링부트 자바버전 오류
- dfs
- BFS
- sql
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함