FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/src/main/java/com/thealgorithms/graph/ZeroOneBfs.java at master · lowtalker/Java · GitHub
lowtalker
Java
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
src
/
main
/
java
/
com
/
thealgorithms
/
graph
/
ZeroOneBfs.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
77 lines (71 loc) · 2.42 KB
Breadcrumbs
Java
/
src
/
main
/
java
/
com
/
thealgorithms
/
graph
/
ZeroOneBfs.java
Copy path
File metadata and controls
77 lines (71 loc) · 2.42 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package
com
.
thealgorithms
.
graph
;
import
java
.
util
.
ArrayDeque
;
import
java
.
util
.
Arrays
;
import
java
.
util
.
Deque
;
import
java
.
util
.
List
;
/**
* 0-1 BFS for shortest paths on graphs with edges weighted 0 or 1.
*
* <p>Time Complexity: O(V + E). Space Complexity: O(V).
*
* <p>References:
* <ul>
* <li>https://cp-algorithms.com/graph/01_bfs.html</li>
* </ul>
*/
public
final
class
ZeroOneBfs
{
private
ZeroOneBfs
() {
// Utility class; do not instantiate.
}
/**
* Computes shortest distances from {@code src} in a graph whose edges have weight 0 or 1.
*
* @param n the number of vertices, labeled {@code 0..n-1}
* @param adj adjacency list; for each vertex u, {@code adj.get(u)} is a list of pairs
* {@code (v, w)} where {@code v} is a neighbor and {@code w} is 0 or 1
* @param src the source vertex
* @return an array of distances; {@code Integer.MAX_VALUE} denotes unreachable
* @throws IllegalArgumentException if {@code n < 0}, {@code src} is out of range,
* or any edge has weight other than 0 or 1
*/
public
static
int
[]
shortestPaths
(
int
n
,
List
<
List
<
int
[]>>
adj
,
int
src
) {
if
(
n
<
0
||
src
<
0
||
src
>=
n
) {
throw
new
IllegalArgumentException
(
"Invalid n or src"
);
}
int
[]
dist
=
new
int
[
n
];
Arrays
.
fill
(
dist
,
Integer
.
MAX_VALUE
);
Deque
<
Integer
>
dq
=
new
ArrayDeque
<>();
dist
[
src
] =
0
;
dq
.
addFirst
(
src
);
while
(!
dq
.
isEmpty
()) {
int
u
=
dq
.
pollFirst
();
List
<
int
[]>
edges
=
adj
.
get
(
u
);
if
(
edges
==
null
) {
continue
;
}
for
(
int
[]
e
:
edges
) {
if
(
e
==
null
||
e
.
length
<
2
) {
continue
;
}
int
v
=
e
[
0
];
int
w
=
e
[
1
];
if
(
v
<
0
||
v
>=
n
) {
continue
;
// ignore bad edges
}
if
(
w
!=
0
&&
w
!=
1
) {
throw
new
IllegalArgumentException
(
"Edge weight must be 0 or 1"
);
}
int
nd
=
dist
[
u
] +
w
;
if
(
nd
<
dist
[
v
]) {
dist
[
v
] =
nd
;
if
(
w
==
0
) {
dq
.
addFirst
(
v
);
}
else
{
dq
.
addLast
(
v
);
}
}
}
}
return
dist
;
}
}
Back
|
FazBrowse Home
|
New Git URL