-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ2178.java
More file actions
97 lines (88 loc) Β· 2.93 KB
/
Q2178.java
File metadata and controls
97 lines (88 loc) Β· 2.93 KB
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
93
94
95
96
97
/**
* Date: 2018. 9. 1.
* Author: inhyuck | https://github.com/inhyuck
* Solution URL: https://github.com/skhucode/skhucode-inhyuck
* Title: λ―Έλ‘ νμ
* Problem: λ―Έλ‘μμ 1μ μ΄λν μ μλ μΉΈμ λνλ΄κ³ , 0μ μ΄λν μ μλ μΉΈμ λνλΈλ€. μ΄λ¬ν λ―Έλ‘κ° μ£Όμ΄μ‘μ λ,
* (1, 1)μμ μΆλ°νμ¬ (N, M)μ μμΉλ‘ μ΄λν λ μ§λμΌ νλ μ΅μμ μΉΈ μλ₯Ό ꡬνλ νλ‘κ·Έλ¨μ μμ±νμμ€.
* URL: https://www.acmicpc.net/problem/2178
*/
package io.inhyuck.graph;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Q2178 {
static int[][] list;
static boolean[][] check;
static int n, m;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
scanner.nextLine();
String temp;
list = new int[n][m];
check = new boolean[n][m];
for (int i = 0; i < n; i++) {
temp = scanner.nextLine();
for (int j = 0; j < m; j++) {
list[i][j] = Integer.parseInt(temp.charAt(j) + "");
}
}
// System.out.println(Arrays.deepToString(list));
bfs(0, 0);
}
private static void bfs(int i, int j) {
Queue<Miro> queue = new LinkedList<>();
check[i][j] = true;
int step = 1;
queue.offer(new Miro(i, j, 1));
while (!queue.isEmpty()) {
// System.out.println(queue.toString());
Miro obj = queue.poll();
if (obj.i > 0 && isOk(obj.i - 1, obj.j)) {
insertQueue(queue, obj.i-1, obj.j, obj.step + 1);
}
if (obj.i < n - 1 && isOk(obj.i + 1, obj.j)) {
insertQueue(queue, obj.i+1, obj.j, obj.step + 1);
}
if (obj.j > 0 && isOk(obj.i, obj.j - 1)) {
insertQueue(queue, obj.i, obj.j-1, obj.step + 1);
}
if (obj.j < m - 1 && isOk(obj.i, obj.j + 1)) {
insertQueue(queue, obj.i, obj.j+1, obj.step + 1);
}
}
}
private static void insertQueue(Queue queue, int i, int j, int step) {
if (i == n - 1 && j == m - 1) {
System.out.println(step);
}
check[i][j] = true;
queue.offer(new Miro(i, j, step));
}
private static boolean isOk(int i, int j) {
if (list[i][j] == 1 && check[i][j] == false) {
return true;
}
return false;
}
private static class Miro {
int i;
int j;
int step;
public Miro(int i, int j, int step) {
this.i = i;
this.j = j;
this.step = step;
}
@Override
public String toString() {
return "Miro{" +
"i=" + i +
", j=" + j +
", step=" + step +
'}';
}
}
}