Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e067f88

Browse files
committed
commit
1 parent 25fd4fb commit e067f88

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed
Binary file not shown.
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import java.util.*;
2+
3+
public class LastDayToCross {
4+
private int[][] directions = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
5+
6+
public boolean canCross(int row, int col, int[][] cells, int day) {
7+
int[][] grid = new int[row][col];
8+
Queue<int[]> queue = new LinkedList<>();
9+
10+
for (int i = 0; i < day; i++) {
11+
grid[cells[i][0] - 1][cells[i][1] - 1] = 1;
12+
}
13+
14+
for (int i = 0; i < col; i++) {
15+
if (grid[0][i] == 0) {
16+
queue.offer(new int[]{0, i});
17+
grid[0][i] = -1;
18+
}
19+
}
20+
21+
while (!queue.isEmpty()) {
22+
int[] cur = queue.poll();
23+
int r = cur[0], c = cur[1];
24+
if (r == row - 1) {
25+
return true;
26+
}
27+
28+
for (int[] dir : directions) {
29+
int newRow = r + dir[0];
30+
int newCol = c + dir[1];
31+
if (newRow >= 0 && newRow < row && newCol >= 0 && newCol < col && grid[newRow][newCol] == 0) {
32+
grid[newRow][newCol] = -1;
33+
queue.offer(new int[]{newRow, newCol});
34+
}
35+
}
36+
}
37+
38+
return false;
39+
}
40+
41+
public int latestDayToCross(int row, int col, int[][] cells) {
42+
int left = 1;
43+
int right = cells.length;
44+
45+
while (left < right) {
46+
int mid = right - (right - left) / 2;
47+
if (canCross(row, col, cells, mid)) {
48+
left = mid;
49+
} else {
50+
right = mid - 1;
51+
}
52+
}
53+
54+
return left;
55+
}
56+
57+
public static void main(String[] args) {
58+
Scanner scanner = new Scanner(System.in);
59+
60+
System.out.print("Enter the number of rows: ");
61+
int row = scanner.nextInt();
62+
63+
System.out.print("Enter the number of columns: ");
64+
int col = scanner.nextInt();
65+
66+
System.out.print("Enter the number of cells: ");
67+
int n = scanner.nextInt();
68+
69+
int[][] cells = new int[n][2];
70+
System.out.println("Enter the cells' coordinates:");
71+
for (int i = 0; i < n; i++) {
72+
System.out.print("Cell " + (i + 1) + ": ");
73+
cells[i][0] = scanner.nextInt();
74+
cells[i][1] = scanner.nextInt();
75+
}
76+
77+
LastDayToCross solution = new LastDayToCross();
78+
int lastDay = solution.latestDayToCross(row, col, cells);
79+
80+
System.out.println("The last day where it is possible to walk from the top to the bottom: " + lastDay);
81+
}
82+
}

0 commit comments

Comments
 (0)