-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq079_WordSearch.java
More file actions
69 lines (63 loc) · 2.11 KB
/
q079_WordSearch.java
File metadata and controls
69 lines (63 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package leetcode_algorithm;
/**
* Given a 2D board and a word, find if the word exists in the grid.
* <p>
* The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
* <p>
* For example,
* Given board =
* <p>
* [
* ['A','B','C','E'],
* ['S','F','C','S'],
* ['A','D','E','E']
* ]
* word = "ABCCED", -> returns true,
* word = "SEE", -> returns true,
* word = "ABCB", -> returns false.
*/
public class q079_WordSearch {
public static void main(String[] args) {
System.out.println(1 ^ 256 ^ 256);
q079_WordSearch solution = new q079_WordSearch();
char[][] board = new char[][]{
{'A', 'B', 'C', 'E'},
{'S', 'F', 'C', 'S'},
{'A', 'D', 'E', 'E'},
{}
};
System.out.println(solution.exist(board, "ABCCED"));
System.out.println(solution.exist(board, "SEE"));
System.out.println(solution.exist(board, "ABCD"));
}
/**
* 解法1
*
* @param board
* @param word
* @return
*/
public boolean exist(char[][] board, String word) {
char[] w = word.toCharArray();
for (int y = 0; y < board.length; y++) {
for (int x = 0; x < board[y].length; x++) {
if (exist(board, y, x, w, 0)) return true;
}
}
return false;
}
private boolean exist(char[][] board, int y, int x, char[] word, int i) {
if (i == word.length) return true;
if (y < 0 || x < 0 || y == board.length || x == board[y].length) return false;
if (board[y][x] != word[i]) return false;
//由于字符的大小不会超过256,故将board[y][x]变成256,标识成已选过
board[y][x] ^= 256;
boolean exist = exist(board, y, x + 1, word, i + 1)
|| exist(board, y, x - 1, word, i + 1)
|| exist(board, y + 1, x, word, i + 1)
|| exist(board, y - 1, x, word, i + 1);
//将字符还原
board[y][x] ^= 256;
return exist;
}
}