Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 27f3ba2

Browse files
solves word search
1 parent cc0aa8e commit 27f3ba2

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272
| 75 | [Sort Colors](https://leetcode.com/problems/sort-colors) | [![Java](assets/java.png)](src/SortColors.java) | |
7373
| 77 | [Combinations](https://leetcode.com/problems/combinations) | [![Java](assets/java.png)](src/Combinations.java) | |
7474
| 78 | [Subsets](https://leetcode.com/problems/subsets) | [![Java](assets/java.png)](src/Subsets.java) | |
75+
| 79 | [Word Search](https://leetcode.com/problems/word-search) | [![Java](assets/java.png)](src/WordSearch.java) | |
7576
| 83 | [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list) | [![Java](assets/java.png)](src/RemoveDuplicatesFromSortedList.java) [![Python](assets/python.png)](python/remove_duplicates_from_linked_list.py) | |
7677
| 88 | [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array) | [![Java](assets/java.png)](src/MergeSortedArray.java) [![Python](assets/python.png)](python/merge_sorted_array.py) | |
7778
| 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [![Java](assets/java.png)](src/BinaryTreeInorderTraversal.java) [![Python](assets/python.png)](python/binary_tree_inorder_traversal.py) | |

src/WordSearch.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// https://leetcode.com/problems/word-search
2+
// T: O(4^{m * n})
3+
// S: O(m * n)
4+
5+
public class WordSearch {
6+
7+
public boolean exist(char[][] board, String word) {
8+
final int rows = board.length, columns = board[0].length;
9+
10+
for (int row = 0; row < rows ; row++) {
11+
for (int column = 0; column < columns ; column++) {
12+
if (exist(board, row, column, word, 0)) {
13+
return true;
14+
}
15+
}
16+
}
17+
18+
return false;
19+
}
20+
21+
private boolean exist(char[][] board, int row, int column, String word, int i) {
22+
if (i == word.length()) return true;
23+
if (row < 0 || column < 0 || row == board.length || column == board[row].length) return false;
24+
if (board[row][column] != word.charAt(i)) return false;
25+
26+
board[row][column] ^= 256;
27+
boolean exist = exist(board, row, column+1, word, i + 1)
28+
|| exist(board, row, column - 1, word, i + 1)
29+
|| exist(board, row + 1, column, word, i + 1)
30+
|| exist(board, row - 1, column, word, i + 1);
31+
32+
board[row][column] ^= 256;
33+
return exist;
34+
}
35+
}

0 commit comments

Comments
 (0)