Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c3e5d17

Browse files
authored
Create WordSearch.java
1 parent 45a8ce1 commit c3e5d17

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

‎Backtracking/WordSearch.java‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//LeetCode 79. Word Search
2+
//Question - https://leetcode.com/problems/word-search/
3+
4+
class Solution {
5+
public boolean exist(char[][] board, String word) {
6+
7+
for(int i = 0 ; i < board.length ; i++){
8+
for(int j = 0 ; j < board[0].length ; j++){
9+
if(helper(board, i, j, word, 0)) return true;
10+
}
11+
}
12+
return false;
13+
}
14+
15+
public boolean helper(char[][] b, int x, int y, String s, int end){
16+
//Base Cases
17+
if(end == s.length()) return true;
18+
19+
if(x < 0 || x >= b.length || y < 0 || y >= b[0].length) return false;
20+
if(b[x][y] != s.charAt(end)) return false;
21+
22+
//Mark as visited
23+
b[x][y] = '#';
24+
25+
//go deeper into recursion
26+
boolean res = helper(b, x+1, y, s, end+1) ||
27+
helper(b, x-1, y, s, end+1) ||
28+
helper(b, x, y+1, s, end+1) ||
29+
helper(b, x, y-1, s, end+1);
30+
//backtarck
31+
b[x][y] = s.charAt(end);
32+
33+
return res;
34+
}
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /