-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
53 lines (42 loc) · 1.18 KB
/
Copy pathsolution.java
File metadata and controls
53 lines (42 loc) · 1.18 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
class Solution {
public List<Integer> exitPoint(int[][] mat) {
int n = mat.length;
int m = mat[0].length;
// Current position
int row = 0, col = 0;
// 0=Right, 1=Down, 2=Left, 3=Up
int dir = 0;
// Continue while inside matrix
while (row >= 0 && row < n && col >= 0 && col < m) {
// If current cell is 1
if (mat[row][col] == 1) {
// Turn right
dir = (dir + 1) % 4;
// Change 1 to 0
mat[row][col] = 0;
}
// Move in current direction
if (dir == 0)
col++;
else if (dir == 1)
row++;
else if (dir == 2)
col--;
else
row--;
}
// Move back to last valid cell
if (dir == 0)
col--;
else if (dir == 1)
row--;
else if (dir == 2)
col++;
else
row++;
List<Integer> ans = new ArrayList<>();
ans.add(row);
ans.add(col);
return ans;
}
}