https://www.acmicpc.net/problem/14940
나의풀이
import java.util.*;
import java.io.*;
public class Main {
static int n,m;
static int[] dx = {0,0,-1,1};
static int[] dy = {-1,1,0,0};
static char[][] map;
static boolean[][] visited;
static int[][] answer;
static public class Node{
int x, y, move;
public Node(int x, int y, int move) {
this.x = x;
this.y = y;
this.move = move;
}
}
public static void bfs(int x, int y){
Queue<Node> q= new LinkedList<>();
q.offer(new Node(x, y, 0));
visited[x][y]=true;
while(!q.isEmpty()){
Node now= q.poll();
// 4방향 상하좌우
for(int i = 0; i < 4; i++) {
int nextX = now.x + dx[i];
int nextY = now.y + dy[i];
// 갈수 없는 위치라면
if(nextX < 0 || nextY < 0 || nextX >= n || nextY >= m) {
continue;
}
//방문한 위치라면
if(visited[nextX][nextY] == true) {
continue;
}
// 갈수없는 땅이면
if(map[nextX][nextY] == '0') {
answer[nextX][nextY] = 0;
continue;
}
answer[nextX][nextY]=now.move + 1;
q.offer(new Node(nextX, nextY, now.move + 1));// 1 증가해서 큐에 넣어주기
visited[nextX][nextY] = true;//방문처리
}
}
}
public static void main(String args[]) throws Exception {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st= new StringTokenizer(br.readLine());
n=Integer.parseInt(st.nextToken());
m=Integer.parseInt(st.nextToken());
map =new char[n][m];
visited= new boolean[n][m];
answer= new int[n][m];
//지도 초기화
for(int i=0;i<n;i++){
st= new StringTokenizer(br.readLine());
for(int j=0;j<m;j++){
map[i][j]= st.nextToken().charAt(0);
}
}
for(int i=0;i<n;i++){
for(int j=0; j<m; j++){
if(map[i][j] == '2'){//여기서 시작
answer[i][j]=0;
bfs(i, j);
}
}
}
//결과출력
for(int i=0;i<n;i++){
for(int j=0; j<m; j++){
if(answer[i][j]==0 && map[i][j] == '1'){
bw.write("-1 ");
}else{
bw.write(answer[i][j]+" ");
}
}
bw.write("\n");
}
bw.flush();
br.close();
bw.close();
}
}
'코테풀이' 카테고리의 다른 글
[백준] BOJ - 14719 빗물 java 자바 (골드5) (0) | 2023.03.13 |
---|---|
[백준] BOJ - 20922 겹치는 건 싫어 자바 java (실버 1) (0) | 2023.03.12 |
[백준] BOJ - 19637 IF문 좀 대신 써줘 자바 java (실버 3) (2) | 2023.03.08 |
[백준] BOJ - 2531 회전 초밥 자바 java (실버1) (0) | 2023.03.02 |
[백준] BOJ - 15989 1, 2, 3 더하기 4 자바 java (실버1) (0) | 2023.03.02 |