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

Commit917936e

Browse files
author
applewjg
committed
Word Search
Change-Id: I38e4be18de4b4725b0ea836653f56a65a6f5f99a
1 parent6515c41 commit917936e

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎WordSearch.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 20, 2014
4+
Problem: Word Search
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/word-search/
7+
Notes:
8+
Given a 2D board and a word, find if the word exists in the grid.
9+
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are
10+
those horizontally or vertically neighboring. The same letter cell may not be used more than once.
11+
For example,
12+
Given board =
13+
[
14+
["ABCE"],
15+
["SFCS"],
16+
["ADEE"]
17+
]
18+
word = "ABCCED", -> returns true,
19+
word = "SEE", -> returns true,
20+
word = "ABCB", -> returns false.
21+
22+
Solution: DFS.
23+
*/
24+
publicclassSolution {
25+
publicbooleanexist(char[][]board,Stringword) {
26+
intm =board.length;
27+
if (m ==0)returnfalse;
28+
intn =board[0].length;
29+
if (n ==0)returnfalse;
30+
if (word.length() ==0)returntrue;
31+
boolean[][]visited =newboolean[m][n];
32+
for (inti =0;i <m; ++i) {
33+
for (intj =0;j <n; ++j) {
34+
if (board[i][j] ==word.charAt(0) &&existRe(board,i,j,word,0,visited)) {
35+
returntrue;
36+
}
37+
}
38+
}
39+
returnfalse;
40+
}
41+
publicbooleanexistRe(char[][]board,inti,intj,Stringword,intcur,boolean[][]visited) {
42+
if (cur ==word.length())returntrue;
43+
intm =board.length;
44+
intn =board[0].length;
45+
if (i <0 ||i >=m ||j <0 ||j >=n)returnfalse;
46+
if (visited[i][j] ==true || (board[i][j] !=word.charAt(cur)))returnfalse;
47+
visited[i][j] =true;
48+
if (existRe(board,i+1,j,word,cur+1,visited))returntrue;
49+
if (existRe(board,i-1,j,word,cur+1,visited))returntrue;
50+
if (existRe(board,i,j+1,word,cur+1,visited))returntrue;
51+
if (existRe(board,i,j-1,word,cur+1,visited))returntrue;
52+
visited[i][j] =false;
53+
returnfalse;
54+
}
55+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp