Movatterモバイル変換


[0]ホーム

URL:


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

Commita1a7a65

Browse files
committed
exist
1 parent46bf021 commita1a7a65

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

‎dfs/Exist.java

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
packageAlgorithms.dfs;
2+
3+
publicclassExist {
4+
publicbooleanexist(char[][]board,Stringword) {
5+
if (board ==null ||word ==null
6+
||board.length ==0 ||board[0].length ==0) {
7+
returnfalse;
8+
}
9+
10+
introws =board.length;
11+
intcols =board[0].length;
12+
13+
boolean[][]visit =newboolean[rows][cols];
14+
15+
// i means the index.
16+
for (inti =0;i <rows;i++) {
17+
for (intj =0;j <cols;j++) {
18+
// dfs all the characters in the matrix
19+
if (dfs(board,i,j,word,0,visit)) {
20+
returntrue;
21+
}
22+
}
23+
}
24+
25+
returnfalse;
26+
}
27+
28+
publicbooleandfs(char[][]board,inti,intj,Stringword,intwordIndex,boolean[][]visit) {
29+
introws =board.length;
30+
intcols =board[0].length;
31+
32+
intlen =word.length();
33+
if (wordIndex >=len) {
34+
returntrue;
35+
}
36+
37+
// the index is out of bound.
38+
if (i <0 ||i >=rows ||j <0 ||j >=cols) {
39+
returnfalse;
40+
}
41+
42+
// the character is wrong.
43+
if (word.charAt(wordIndex) !=board[i][j]) {
44+
returnfalse;
45+
}
46+
47+
// 不要访问访问过的节点
48+
if (visit[i][j] ==true) {
49+
returnfalse;
50+
}
51+
52+
visit[i][j] =true;
53+
54+
// 递归
55+
// move down
56+
if (dfs(board,i +1,j,word,wordIndex +1,visit)) {
57+
returntrue;
58+
}
59+
60+
// move up
61+
if (dfs(board,i -1,j,word,wordIndex +1,visit)) {
62+
returntrue;
63+
}
64+
65+
// move right
66+
if (dfs(board,i,j +1,word,wordIndex +1,visit)) {
67+
returntrue;
68+
}
69+
70+
// move left
71+
if (dfs(board,i,j -1,word,wordIndex +1,visit)) {
72+
returntrue;
73+
}
74+
75+
// 回溯
76+
visit[i][j] =false;
77+
returnfalse;
78+
}
79+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp