Skip to content

Commit 1cab136

Browse files
committed
solve 79.word-search
1 parent e283c68 commit 1cab136

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

vscode/79.word-search.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* @lc app=leetcode id=79 lang=java
3+
*
4+
* [79] Word Search
5+
*
6+
* https://leetcode.com/problems/word-search/description/
7+
*
8+
* algorithms
9+
* Medium (32.15%)
10+
* Likes: 2097
11+
* Dislikes: 107
12+
* Total Accepted: 317.7K
13+
* Total Submissions: 988K
14+
* Testcase Example: '[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]\n"ABCCED"'
15+
*
16+
* Given a 2D board and a word, find if the word exists in the grid.
17+
*
18+
* The word can be constructed from letters of sequentially adjacent cell,
19+
* where "adjacent" cells are those horizontally or vertically neighboring. The
20+
* same letter cell may not be used more than once.
21+
*
22+
* Example:
23+
*
24+
*
25+
* board =
26+
* [
27+
* ⁠ ['A','B','C','E'],
28+
* ⁠ ['S','F','C','S'],
29+
* ⁠ ['A','D','E','E']
30+
* ]
31+
*
32+
* Given word = "ABCCED", return true.
33+
* Given word = "SEE", return true.
34+
* Given word = "ABCB", return false.
35+
*
36+
*
37+
*/
38+
class Solution {
39+
public boolean exist(char[][] board, String word) {
40+
for (int i = 0; i < board.length; i++) {
41+
for (int j = 0; j < board[i].length; j++) {
42+
if (exist(board, i, j, word, 0)) {
43+
return true;
44+
}
45+
}
46+
}
47+
return false;
48+
}
49+
50+
public boolean exist(char[][] board, int i, int j, String word, int pos) {
51+
if (pos == word.length()) return true;
52+
if (i < 0 || i > board.length - 1 || j < 0 || j > board[i].length - 1) return false;
53+
if (board[i][j] != word.charAt(pos)) return false;
54+
board[i][j] = '*';
55+
boolean result = exist(board, i - 1, j, word, pos + 1)
56+
|| exist(board, i + 1, j, word, pos + 1)
57+
|| exist(board, i, j - 1, word, pos + 1)
58+
|| exist(board, i, j + 1, word, pos + 1);
59+
board[i][j] = word.charAt(pos);
60+
return result;
61+
}
62+
}
63+

0 commit comments

Comments
 (0)