FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-interview-patterns/java/Graphs/CountIslands.java at main · iamthatdev/coding-interview-patterns · GitHub
iamthatdev
/
coding-interview-patterns
Public
forked from
ByteByteGoHq/coding-interview-patterns
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-interview-patterns
/
java
/
Graphs
/
CountIslands.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
39 lines (37 loc) · 1.41 KB
Breadcrumbs
coding-interview-patterns
/
java
/
Graphs
/
CountIslands.java
Copy path
File metadata and controls
39 lines (37 loc) · 1.41 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
public
class
CountIslands
{
public
int
countIslands
(
int
[][]
matrix
) {
if
(
matrix
==
null
||
matrix
.
length
==
0
||
matrix
[
0
] ==
null
||
matrix
[
0
].
length
==
0
) {
return
0
;
}
int
count
=
0
;
for
(
int
r
=
0
;
r
<
matrix
.
length
;
r
++) {
for
(
int
c
=
0
;
c
<
matrix
[
0
].
length
;
c
++) {
// If a land cell is found, perform DFS to explore the full
// island, and include this island in our count.
if
(
matrix
[
r
][
c
] ==
1
) {
dfs
(
r
,
c
,
matrix
);
count
++;
}
}
}
return
count
;
}
private
void
dfs
(
int
r
,
int
c
,
int
[][]
matrix
) {
// Mark the current land cell as visited.
matrix
[
r
][
c
] = -
1
;
// Define direction vectors for up, down, left, and right.
int
[][]
dirs
=
new
int
[][]{{-
1
,
0
}, {
1
,
0
}, {
0
, -
1
}, {
0
,
1
}};
// Recursively call DFS on each neighboring land cell to continue
// exploring this island.
for
(
int
[]
d
:
dirs
) {
int
nextR
=
r
+
d
[
0
];
int
nextC
=
c
+
d
[
1
];
if
(
isWithinBounds
(
nextR
,
nextC
,
matrix
) &&
matrix
[
nextR
][
nextC
] ==
1
) {
dfs
(
nextR
,
nextC
,
matrix
);
}
}
}
private
boolean
isWithinBounds
(
int
r
,
int
c
,
int
[][]
matrix
) {
return
0
<=
r
&&
r
<
matrix
.
length
&&
0
<=
c
&&
c
<
matrix
[
0
].
length
;
}
}
Back
|
FazBrowse Home
|
New Git URL