Skip to content

Commit e0aa3f5

Browse files
committed
update 79 java
1 parent 841ba30 commit e0aa3f5

File tree

3 files changed

+162
-30
lines changed

3 files changed

+162
-30
lines changed

leetcode_java/src/main/java/LeetCodeJava/BackTrack/WordSearch.java

Lines changed: 82 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -130,28 +130,89 @@ private boolean dfs_(char[][] board, int y, int x, int idx, String word, boolean
130130
visited[y][x] = true;
131131

132132
int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
133-
/**
134-
* NOTE !!!
135-
*
136-
* instead of below structure:
137-
*
138-
* boolean didFindNextCharacter =
139-
* dfs2(row + 1, col, word, lvl + 1, visited, board) ||
140-
* dfs2(row - 1, col, word, lvl + 1, visited, board) ||
141-
* dfs2(row, col + 1, word, lvl + 1, visited, board) ||
142-
* dfs2(row, col - 1, word, lvl + 1, visited, board);
143-
*
144-
* we can use below logic as well:
145-
*
146-
* for (int[] dir : dirs) {
147-
* if (dfs_(board, y + dir[0], x + dir[1], idx + 1, word, visited)) {
148-
* return true;
149-
* }
150-
* }
151-
*
152-
*/
153-
for (int[] dir : dirs) {
133+
/**
134+
* NOTE !!!
135+
*
136+
* instead of below structure:
137+
*
138+
* boolean didFindNextCharacter =
139+
* dfs2(row + 1, col, word, lvl + 1, visited, board) ||
140+
* dfs2(row - 1, col, word, lvl + 1, visited, board) ||
141+
* dfs2(row, col + 1, word, lvl + 1, visited, board) ||
142+
* dfs2(row, col - 1, word, lvl + 1, visited, board);
143+
*
144+
* we can use below logic as well:
145+
*
146+
* for (int[] dir : dirs) {
147+
* if (dfs_(board, y + dir[0], x + dir[1], idx + 1, word, visited)) {
148+
* return true;
149+
* }
150+
* }
151+
*/
152+
/**
153+
* 1) Detailed Explanation:
154+
*
155+
* Role of return true in the Loop
156+
*
157+
* 1. Backtracking Recursion:
158+
* • The function backtrack is called recursively to explore possible paths in the grid.
159+
* • Each recursive call either returns true if the word can be constructed from the current path or false if it cannot.
160+
*
161+
* 2. Returning Early:
162+
* • As soon as one of the recursive calls returns true (indicating the word has been found), there is no need to continue exploring other directions. The word has already been successfully constructed.
163+
*
164+
* 3. Efficiency:
165+
* • Exiting the loop early saves computation by avoiding exploration of unnecessary paths.
166+
*
167+
*
168+
* 2) What Happens Without return true?
169+
*
170+
* -> If the return true is omitted, the function will:
171+
* 1. Continue to check all remaining directions in the directions array, even after finding a valid path.
172+
* 2. Complete all recursive calls, backtrack, and ultimately return false for the current recursion level, even if a valid path exists deeper in the recursion tree.
173+
*
174+
* -> This would result in the algorithm failing to detect that the word is present in the grid.
175+
*
176+
*
177+
* 3) Example:
178+
* Let’s consider a small grid:
179+
*
180+
* board = [
181+
* ['A', 'B'],
182+
* ['C', 'D']
183+
* ];
184+
* word = "AB";
185+
*
186+
*
187+
* Start at (0, 0) (value A), matching the first character.
188+
* • Check neighbors:
189+
* • Move right to (0, 1) (value B), matching the second character. At this point, the word is found, so we return true.
190+
*
191+
* With return true:
192+
* • When the recursive call to (0, 1) returns true, the loop exits immediately, and the function propagates true all the way up.
193+
*
194+
* Without return true:
195+
* • Even after (0, 1) finds the word, the function continues checking other directions (down, left, up), wasting computation. Eventually, it backtracks, losing the valid result.
196+
*
197+
*
198+
*
199+
*
200+
*
201+
* 4) Conclusion
202+
*
203+
* Returning true immediately when a valid path is found is
204+
* both correct and efficient. It skips redundant exploration
205+
* and ensures that the recursion terminates as soon as the word is found.
206+
* Other recursive logic is unaffected since the backtracking process
207+
* stops as soon as we achieve the goal.
208+
*
209+
*/
210+
for (int[] dir : dirs) {
154211
if (dfs_(board, y + dir[0], x + dir[1], idx + 1, word, visited)) {
212+
/** NOTE !!!
213+
*
214+
* need to return true IMMEDIATELY if a true solution is found
215+
*/
155216
return true;
156217
}
157218
}

leetcode_java/src/main/java/dev/workspace6.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -599,5 +599,62 @@ public int[][] multiply(int[][] mat1, int[][] mat2) {
599599
return res;
600600
}
601601

602+
// LC 079
603+
// https://leetcode.com/problems/word-search/
604+
// 2.31 pm - 2.45 pm
605+
public boolean exist(char[][] board, String word) {
606+
607+
if (board.length == 1 && board[0].length == 1){
608+
return String.valueOf(board[0][0]).equals(word);
609+
}
610+
611+
// backtrack
612+
Set<List<Integer>> visited = new HashSet<>();
613+
int l = board.length;
614+
int w = board[0].length;
615+
for(int i = 0; i < l; i++){
616+
for(int j = 0; j < w; j++){
617+
StringBuilder sb = new StringBuilder();
618+
if(canFind(board, word, j, i, sb, visited)){
619+
return true;
620+
}
621+
}
622+
}
623+
624+
return false;
625+
}
626+
627+
private boolean canFind(char[][] board, String word, int x, int y, StringBuilder cur, Set<List<Integer>> visited){
628+
int l = board.length;
629+
int w = board[0].length;
630+
int[][] moves = new int[][]{ {0,1}, {0,-1}, {1,0}, {-1,0} };
631+
if (cur.toString().length() == word.length() && cur.toString().equals(word)){
632+
return true;
633+
}
634+
if (cur.toString().length() > word.length()){
635+
return false; // ??
636+
}
637+
638+
for (int[] move: moves){
639+
int x_ = x + move[0];
640+
int y_ = y + move[1];
641+
List<Integer> tmp = new ArrayList<>();
642+
tmp.add(x);
643+
tmp.add(y);
644+
String tmpVal = String.valueOf(board[y_][x_]);
645+
if (x_ >= 0 && x_ < w && y_ >= 0 &&
646+
y_ < l && !visited.contains(tmp) &&
647+
tmpVal.equals(word.charAt(cur.length()+1))){
648+
visited.add(tmp);
649+
cur.append(board[y][x]); // ???
650+
canFind(board, word, x_, y_, cur, visited);
651+
// undo
652+
cur.deleteCharAt(cur.toString().length() - 1);
653+
visited.remove(tmp); // ??
654+
}
655+
}
656+
657+
return false;
658+
}
602659

603660
}

leetcode_java/src/main/java/dev/workspace7.java

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package dev;
22

3+
import java.util.ArrayList;
34
import java.util.Arrays;
5+
import java.util.List;
46

57
public class workspace7 {
68
public static void main(String[] args) {
@@ -16,15 +18,27 @@ public static void main(String[] args) {
1618
// }
1719

1820
// ------------------- TEST 2
19-
int[][] mat1 = new int[][]{ {1,0,0}, {-1,0,3} };
20-
int[][] mat2 = new int[][]{ {7,0,0}, {0,0,0}, {0,0,1} };
21-
int[][] res = multiply(mat1, mat2);
22-
System.out.println(">>> res = ");
23-
for (int i = 0; i < res.length; i++){
24-
for (int j = 0; j < res[0].length; j++){
25-
System.out.println(res[i][j]);
26-
}
27-
}
21+
// int[][] mat1 = new int[][]{ {1,0,0}, {-1,0,3} };
22+
// int[][] mat2 = new int[][]{ {7,0,0}, {0,0,0}, {0,0,1} };
23+
// int[][] res = multiply(mat1, mat2);
24+
// System.out.println(">>> res = ");
25+
// for (int i = 0; i < res.length; i++){
26+
// for (int j = 0; j < res[0].length; j++){
27+
// System.out.println(res[i][j]);
28+
// }
29+
// }
30+
31+
// ------------------- TEST 3
32+
// String a = "a";
33+
// String b = "b";
34+
// a += b;
35+
// System.out.println(">> a = " + a);
36+
37+
// ------------------- TEST 4
38+
List<String> x = new ArrayList<>();
39+
x.add("a");
40+
x.add("b");
41+
System.out.println(x.toString());
2842
}
2943

3044

0 commit comments

Comments
 (0)