FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-Interview/WordLadder.java at master · arjunmullick/coding-Interview · GitHub
arjunmullick
/
coding-Interview
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
3
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-Interview
/
WordLadder.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
55 lines (47 loc) · 1.82 KB
Breadcrumbs
coding-Interview
/
WordLadder.java
Copy path
File metadata and controls
55 lines (47 loc) · 1.82 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
com
.
leetcode
;
import
java
.
util
.
HashSet
;
import
java
.
util
.
LinkedList
;
import
java
.
util
.
List
;
import
java
.
util
.
Queue
;
/**
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
*/
public
class
WordLadder
{
//https://leetcode.com/problems/word-ladder/
//BFS on all possibility O(N * K*K) N words and each word with K length
class
Solution
{
public
int
ladderLength
(
String
beginWord
,
String
endWord
,
List
<
String
>
wordList
) {
if
(
beginWord
.
equals
(
endWord
))
return
1
;
HashSet
<
String
>
visited
=
new
HashSet
<>();
int
result
=
1
;
Queue
<
String
>
queue
=
new
LinkedList
<>();
queue
.
offer
(
beginWord
);
while
(
queue
.
size
() >
0
){
Queue
<
String
>
nextLevel
=
new
LinkedList
<>();
while
(
queue
.
size
() >
0
){
String
w
=
queue
.
poll
();
if
(
w
.
equals
(
endWord
))
return
result
;
for
(
String
next
:
wordList
){
if
(!
visited
.
contains
(
next
) &&
isOneDiff
(
w
,
next
)){
nextLevel
.
offer
(
next
);
visited
.
add
(
next
);
//adding here is better vs when poll. Avoids checks in same level
}
}
}
result
++;
queue
=
nextLevel
;
}
return
0
;
}
public
boolean
isOneDiff
(
String
w1
,
String
w2
){
if
(
w1
.
length
() !=
w2
.
length
())
return
false
;
int
count
=
0
;
for
(
int
i
=
0
;
i
<
w2
.
length
();
i
++){
if
(
w1
.
charAt
(
i
) !=
w2
.
charAt
(
i
))
count
++;
}
return
count
==
1
;
}
}
}
Back
|
FazBrowse Home
|
New Git URL