-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExit point in a matrix
94 lines (74 loc) · 2.34 KB
/
Exit point in a matrix
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
//Exit point in a matrix
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while(T-- > 0) {
String[] s = br.readLine().trim().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
int[][] matrix = new int[n][m];
for(int i = 0; i < n; i++) {
String[] S = br.readLine().split(" ");
for(int j = 0; j < m; j++) {
matrix[i][j] = Integer.parseInt(S[j]);
}
}
Solution ob = new Solution();
int[] ans = ob.FindExitPoint(n, m, matrix);
for(int i = 0; i < ans.length; i++)
System.out.print(ans[i] + " ");
System.out.println();
}
}
}
class Solution {
public int[] FindExitPoint(int n, int m, int[][] matrix) {
int[] ans = new int[2];
int i = 0, j = 0, count = 0;
int previ = 0, prevj = 0;
while(j > -1 && j < m && i > -1 && i < n) {
previ = i;
prevj = j;
if(matrix[i][j] == 1) {
matrix[i][j] = 0;
if(count == 0) {
i++;
count = 1;
}
else if(count == 1) {
j--;
count = 2;
}
else if(count == 2) {
i--;
count = 3;
}
else if(count == 3) {
count = 0;
j++;
}
}
else {
if(count == 0) {
j++;
}
else if(count == 1) {
i++;
}
else if(count == 2) {
j--;
}
else {
i--;
}
}
}
ans[0] = previ;
ans[1] = prevj;
return ans;
}
}