-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCrossTheMaze.java
More file actions
91 lines (90 loc) · 2.17 KB
/
CrossTheMaze.java
File metadata and controls
91 lines (90 loc) · 2.17 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
package codechef;
import java.io.*;
public class CrossTheMaze {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t>0){
String NM[] = new String[2];
NM = br.readLine().split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
short maze[][] = new short[N][M];
short mincount[][] = new short[N][M];
boolean validity[][] = new boolean[N][M];
char m[] = new char[M];
for(int i = 0 ; i<N ; i++){
m = br.readLine().toCharArray();
for(int j = 0; j<M ; j++){
maze[i][j] = (short)(m[j]-'0');
}
}
validity[0][0] =true;
mincount[0][0]++;
for(int i = 1 ; i<N ; i++){
if((i-1)>=0 && maze[i-1][0]!=maze[i][0]){
validity[i][0] = true;
}else{
break;
}
}
for(int i = 1 ; i<N ; i++){
if(validity[i][0]){
mincount[i][0]+=mincount[i-1][0];
}else{
break;
}
}
for(int i = 1 ; i<M ; i++){
if((i-1)>=0 && maze[0][i-1]!=maze[0][i]){
validity[0][i] = true;
}else{
break;
}
}
for(int i = 1 ; i<M ; i++){
if(validity[0][i]){
mincount[0][i]+=mincount[0][i-1];
}else{
break;
}
}
for(int j =1 ; j<M ; j++){
for(int i = 1 ; i<N ; i++){
if(maze[i][j-1]!=maze[i][j] || maze[i-1][j]!=maze[i][j]){
validity[i][j] = true;
}else{
break;
}
}
for(int i = 1 ; i<N ; i++){
if(validity[i][j-1] && validity[i-1][j]){
mincount[i][j] = min(mincount[i-1][j],mincount[i][j-1]);
mincount[i][j]++;
}else if(validity[i-1][j]){
if(maze[i][j-1]!=maze[i][j]){
mincount[i][j] = mincount[i-1][j];
mincount[i][j]++;
}
}else if(validity[i][j-1]){
if(maze[i-1][j]!=maze[i][j]){
mincount[i][j] = mincount[i][j-1];
mincount[i][j]++;
}
}else{
mincount[i][j] = 0;
}
}
}
if(mincount[N-1][M-1]>1){
System.out.println(mincount[N-1][M-1]);
}else{
System.out.println("-1");
}
t--;
}
}
public static short min(short a, short b){
return a>b ? a : b;
}
}