-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem1261.java
More file actions
71 lines (62 loc) · 1.96 KB
/
Problem1261.java
File metadata and controls
71 lines (62 loc) · 1.96 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
import java.util.PriorityQueue;
import java.util.Scanner;
public class Problem1261 {
static int n, m;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
String t = sc.next();
for (int j = 0; j < n; j++)
arr[i][j] = t.charAt(j) - '0';
}
visited = new boolean[m][n];
System.out.println(solve(arr));
sc.close();
}
static int[][] dir = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };
static boolean[][] visited;
private static int solve(int[][] arr) {
PriorityQueue<Pair> queue = new PriorityQueue<>();
queue.add(new Pair(0, 0, 0));
visited[0][0] = true;
int min = Integer.MAX_VALUE;
while (!queue.isEmpty()) {
Pair t = queue.poll();
if (t.x == m - 1 && t.y == n - 1) {
min = Math.min(min, t.cnt);
break;
}
for (int i = 0; i < 4; i++) {
int tx = t.x + dir[i][0];
int ty = t.y + dir[i][1];
if (tx < 0 || ty < 0 || ty >= n || tx >= m)
continue;
if (visited[tx][ty])
continue;
visited[tx][ty] = true;
if (arr[tx][ty] == 1)
queue.add(new Pair(tx, ty, t.cnt + 1));
else
queue.add(new Pair(tx, ty, t.cnt));
}
}
return min;
}
static class Pair implements Comparable<Pair> {
private int x;
private int y;
private int cnt;
public Pair(int x, int y, int cnt) {
this.x = x;
this.y = y;
this.cnt = cnt;
}
@Override
public int compareTo(Pair o) {
return cnt > o.cnt ? 1 : cnt == o.cnt ? 0 : -1;
}
}
}