FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaArithmetic/src/LeetCode/LeetCode200.java at master · wpq2014/JavaArithmetic · GitHub
wpq2014
JavaArithmetic
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaArithmetic
/
src
/
LeetCode
/
LeetCode200.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
77 lines (59 loc) · 2 KB
Breadcrumbs
JavaArithmetic
/
src
/
LeetCode
/
LeetCode200.java
Copy path
File metadata and controls
77 lines (59 loc) · 2 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
LeetCode
;
public
class
LeetCode200
{
//https://leetcode-cn.com/problems/number-of-islands/description/
/// 时间复杂度: O(n*m)
/// 空间复杂度: O(n*m)
private
int
d
[][] = {{
0
,
1
}, {
1
,
0
}, {
0
, -
1
}, {-
1
,
0
}};
private
int
m
,
n
;
private
boolean
visited
[][];
public
int
numIslands
(
char
[][]
grid
) {
if
(
grid
==
null
||
grid
.
length
==
0
||
grid
[
0
].
length
==
0
)
return
0
;
m
=
grid
.
length
;
n
=
grid
[
0
].
length
;
visited
=
new
boolean
[
m
][
n
];
int
res
=
0
;
for
(
int
i
=
0
;
i
<
m
;
i
++)
for
(
int
j
=
0
;
j
<
n
;
j
++)
if
(
grid
[
i
][
j
] ==
'1'
&& !
visited
[
i
][
j
]) {
dfs
(
grid
,
i
,
j
);
res
++;
}
return
res
;
}
// 从grid[x][y]的位置开始,进行floodfill
// 保证(x,y)合法,且grid[x][y]是没有被访问过的陆地
private
void
dfs
(
char
[][]
grid
,
int
x
,
int
y
) {
//assert(inArea(x,y));
visited
[
x
][
y
] =
true
;
for
(
int
i
=
0
;
i
<
4
;
i
++) {
int
newx
=
x
+
d
[
i
][
0
];
int
newy
=
y
+
d
[
i
][
1
];
if
(
inArea
(
newx
,
newy
) && !
visited
[
newx
][
newy
] &&
grid
[
newx
][
newy
] ==
'1'
)
dfs
(
grid
,
newx
,
newy
);
}
return
;
}
private
boolean
inArea
(
int
x
,
int
y
) {
return
x
>=
0
&&
x
<
m
&&
y
>=
0
&&
y
<
n
;
}
public
static
void
main
(
String
[]
args
) {
char
grid1
[][] = {
{
'1'
,
'1'
,
'1'
,
'1'
,
'0'
},
{
'1'
,
'1'
,
'0'
,
'1'
,
'0'
},
{
'1'
,
'1'
,
'0'
,
'0'
,
'0'
},
{
'0'
,
'0'
,
'0'
,
'0'
,
'0'
}
};
System
.
out
.
println
((
new
LeetCode200
()).
numIslands
(
grid1
));
// 1
// ---
char
grid2
[][] = {
{
'1'
,
'1'
,
'0'
,
'0'
,
'0'
},
{
'1'
,
'1'
,
'0'
,
'0'
,
'0'
},
{
'0'
,
'0'
,
'1'
,
'0'
,
'0'
},
{
'0'
,
'0'
,
'0'
,
'1'
,
'1'
}
};
System
.
out
.
println
((
new
LeetCode200
()).
numIslands
(
grid2
));
// 3
}
}
Back
|
FazBrowse Home
|
New Git URL