β¨ BFS + DFS + μμ νμ
https://www.acmicpc.net/problem/14502
14502λ²: μ°κ΅¬μ
μΈμ²΄μ μΉλͺ μ μΈ λ°μ΄λ¬μ€λ₯Ό μ°κ΅¬νλ μ°κ΅¬μμμ λ°μ΄λ¬μ€κ° μ μΆλμλ€. λ€νν λ°μ΄λ¬μ€λ μμ§ νΌμ§μ§ μμκ³ , λ°μ΄λ¬μ€μ νμ°μ λ§κΈ° μν΄μ μ°κ΅¬μμ λ²½μ μΈμ°λ €κ³ νλ€. μ°κ΅¬μλ ν¬
www.acmicpc.net
πκ³ λ €ν΄μΌν μ
- λ²½μ 3κ° μΈμ΄λ€. β μΌμΌμ΄ 3κ°μ λ²½μ μΈμλ³Έ ν λ°μ΄λ¬μ€λ₯Ό νΌλ¨λ € μμ μμμ΄ μ΅λμΈ κ²½μ°λ₯Ό ꡬνλ€. (λ°±νΈλνΉ + μμ νμ)
- λ²½μ 3κ° μΈμ΄ ν λ°μ΄λ¬μ€κ° νΌμ§λ κ²½μ°λ λ€μνλ―λ‘ λ³΅μ¬λ³Έμ λ§λ€μ΄μ ꡬνλ€.
πΉοΈ νμ΄κ³Όμ
1οΈβ£ λ°μ΄λ¬μ€μ λ²½μ΄ μλ κ³³μ μ 보λ₯Ό 2μ°¨μ λ°°μ΄μ μ μ₯νλ€.
2οΈβ£ λ²½μ μΈμ΄λ€. β 3κ°μ λ²½μ μΈμμΌ νλ―λ‘ μ‘°ν©μ μκ°νλ©΄ λλ€. DFSμ λ°±νΈλνΉμ μ΄μ©ν΄ λ²½μ μΈμ°λ©΄ λλ€.
3οΈβ£ 3κ°μ λ²½μ΄ μΈμμ§λ©΄ λ°μ΄λ¬μ€λ₯Ό νΌλ¨λ¦°λ€. λ°μ΄λ¬μ€κ° μλ κ³³λΆν° μμν΄ νΌμ§λ―λ‘ λ°μ΄λ¬μ€κ° μλ κ³³μ μ 보λ₯Ό λ°λ‘ μ μ₯ν΄μΌ νλ€.
4οΈβ£ 3κ°μ λ²½μ΄ μΈμμ§λ κ²½μ°λ λ§€λ² λ¬λΌμ§λ―λ‘ 2μ°¨μ λ°°μ΄μ 볡μ¬ν΄μ μ¬μ©νλ€.
5οΈβ£ λ°μ΄λ¬μ€κ° λ€ νΌμ‘μΌλ©΄ μμ μμμ ꡬνλ€.
π©π» μ 체 μ½λ
public class BOJ_14502_μ°κ΅¬μ {
static int N, M;
static int max = Integer.MIN_VALUE;
static int[][] lab;
static int[] dx = {0, 0, 1, -1};
static int[] dy = {1, -1, 0, 0};
static class Info{
int x, y;
public Info(int x, int y) {
this.x = x;
this.y = y;
}
}
//DFS
static void makeWall(int depth){
if (depth == 3) {
spreadVirus();
return;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (lab[i][j] ==0) {
lab[i][j]=1;
makeWall(depth + 1);
lab[i][j]=0;
}
}
}
}
// BFS
static void spreadVirus(){
Queue<Info> queue = new LinkedList<>();
int[][] virusMap = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
virusMap[i][j] = lab[i][j];
if (virusMap[i][j] == 2) {
queue.add(new Info(i, j));
}
}
}
while (!queue.isEmpty()) {
Info now = queue.poll();
for (int i = 0; i < 4; i++) {
int nx = now.x + dx[i];
int ny = now.y + dy[i];
if (nx >= 0 && ny >= 0 && nx < N && ny < M && virusMap[nx][ny]==0) {
virusMap[nx][ny] = 2;
queue.add(new Info(nx, ny));
}
}
}
int cnt=0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (virusMap[i][j] == 0) {
cnt++;
}
}
}
max = Math.max(cnt, max);
}
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());
lab = new int[N][M];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
lab[i][j] = Integer.parseInt(st.nextToken());
}
}
makeWall(0);
bw.write(max + " ");
bw.flush();
bw.close();
}
}
'μκ³ λ¦¬μ¦ > BOJ' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[BOJ] 18352 νΉμ 거리μ λμ μ°ΎκΈ° - Java (0) | 2023.12.04 |
---|---|
[BOJ] 4179 λΆ! - Java (1) | 2023.10.25 |
[BOJ] 3190 λ± (0) | 2023.09.25 |
[BOJ] 11657 νμλ¨Έμ (1) | 2023.09.08 |
[BOJ] 1865 μν (0) | 2023.09.08 |