[백준] 16946 벽 부수고 이동하기4

`

bfs + backtracking


 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class B16946 {
	static int N,M;
	static int[][] arr, dp,  delta = {{1,0},{0,1},{-1,0},{0,-1}};
	static boolean[][] visit, check;
	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];
		dp = new int[N][M];
		visit = new boolean[N][M]; // 전체 체크
		check = new boolean[N][M]; // 벽 체크
		
		for(int i=0;i<N;i++) {
			String[] s = br.readLine().split("");
			for(int j=0;j<M;j++) {
				arr[i][j] = Integer.parseInt(s[j]);
			}
		}
		
		for(int i=0;i<N;i++) {
			for(int j=0;j<M;j++) {
				if(arr[i][j]==0 && !visit[i][j]) {
					search(i,j);
				}else if(arr[i][j]==1) {
					dp[i][j]+=1;
				}
			}
		}
		
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < N; i++) {
			for(int j = 0; j < M; j++) {
				sb.append(dp[i][j]%10);
			}
			sb.append("\n");
		}
		System.out.println(sb);
	}
	
	private static void search(int x, int y) {
		Queue<int []> q1 = new LinkedList<>(); // 영역 찾기 큐
		Queue<int []> q2 = new LinkedList<>(); // 영역에 인접한 벽 찾기 큐
		q1.add(new int[] {x,y});
		
		visit[x][y] = true;
		int cnt = 1;
		
		while(!q1.isEmpty()) {
			int[] point = q1.poll();
			
			for(int d=0;d<4;d++) {
				int nx = point[0] + delta[d][0];
				int ny = point[1] + delta[d][1];
				
				if(!inside(nx,ny) || visit[nx][ny]) continue; 
				
				if(arr[nx][ny]==1) {
					if(!check[nx][ny]) {
						q2.add(new int[] {nx,ny}); // 주위에 벽 있고 check 아닌 경우 q2에 추가
						check[nx][ny] = true;
					}
					continue;
				}
				
				cnt++; // 영역 넓이
				visit[nx][ny] = true;
				q1.add(new int[]{nx,ny}); 
					
			}
		}
		
		while(!q2.isEmpty()) { // 벽에 영역 넓이를 더해줌
			int[] point = q2.poll();
			dp[point[0]][point[1]] +=cnt;
			check[point[0]][point[1]] = false;
		}
	}

	private static boolean inside(int x, int y) {
		return x >= 0 && x < N && y >= 0 && y < M;
	}
}
updatedupdated2021-03-302021-03-30
Load Comments?