Skip to content

Commit d2df2f2

Browse files
authored
Merge pull request #77 from Rishabh4321/Rishabh4321-patch-1
Created LeeAlgorithm Optimized solution in java
2 parents 53c2336 + 95474ac commit d2df2f2

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

LeeAlgorithmOptimized.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import java.util.LinkedList;
2+
import java.util.Queue;
3+
4+
public class LeeAlgorithmOptimized {
5+
6+
private static final int[] dx = {-1, 0, 1, 0}; // Array to represent movements in the x-axis
7+
private static final int[] dy = {0, 1, 0, -1}; // Array to represent movements in the y-axis
8+
9+
private static boolean isValid(int[][] matrix, int row, int col, boolean[][] visited) {
10+
int numRows = matrix.length;
11+
int numCols = matrix[0].length;
12+
// Check if the position is within the matrix bounds and not visited before
13+
return (row >= 0 && row < numRows && col >= 0 && col < numCols && matrix[row][col] == 0 && !visited[row][col]);
14+
}
15+
16+
public static void leeAlgorithm(int[][] matrix, int startX, int startY) {
17+
int numRows = matrix.length;
18+
int numCols = matrix[0].length;
19+
boolean[][] visited = new boolean[numRows][numCols];
20+
Queue<Integer> queueX = new LinkedList<>();
21+
Queue<Integer> queueY = new LinkedList<>();
22+
23+
queueX.add(startX); // Initialize the queues with the start position
24+
queueY.add(startY);
25+
visited[startX][startY] = true;
26+
27+
while (!queueX.isEmpty()) {
28+
int x = queueX.poll(); // Get the current position
29+
int y = queueY.poll();
30+
31+
for (int i = 0; i < 4; i++) {
32+
int newX = x + dx[i]; // Calculate the new position
33+
int newY = y + dy[i];
34+
35+
if (isValid(matrix, newX, newY, visited)) {
36+
queueX.add(newX); // Add the new position to the queue
37+
queueY.add(newY);
38+
visited[newX][newY] = true;
39+
matrix[newX][newY] = -1; // Mark the position as visited
40+
}
41+
}
42+
}
43+
}
44+
45+
public static void main(String[] args) {
46+
int[][] matrix = {
47+
{0, 0, 0, 0, 0},
48+
{0, 1, 1, 1, 0},
49+
{0, 1, 0, 0, 0},
50+
{0, 1, 1, 1, 0},
51+
{0, 0, 0, 0, 0}
52+
};
53+
54+
int startX = 1;
55+
int startY = 1;
56+
57+
leeAlgorithm(matrix, startX, startY);
58+
59+
// Print the modified matrix after running the algorithm
60+
for (int i = 0; i < matrix.length; i++) {
61+
for (int j = 0; j < matrix[0].length; j++) {
62+
System.out.print(matrix[i][j] + " ");
63+
}
64+
System.out.println();
65+
}
66+
}
67+
}

0 commit comments

Comments
 (0)