Skip to content

Commit ea68d4f

Browse files
committed
add number of islands
1 parent 8bed653 commit ea68d4f

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

number-of-islands/README.md

Whitespace-only changes.

number-of-islands/Solution.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
public class Solution {
2+
3+
boolean allowed(int x, int y, final int mx, final int my, char[][] grid, boolean[][] visited){
4+
return (x < mx) && (x >= 0)
5+
&& (y < my) && (y >= 0)
6+
&& (grid[x][y] == '1')
7+
&& (!visited[x][y]);
8+
}
9+
10+
void travel(int x, int y, final int mx, final int my, char[][] grid, boolean[][] visited){
11+
12+
// x - 1, y
13+
// x + 1, y
14+
// x, y - 1
15+
// x, y + 1
16+
17+
visited[x][y] = true;
18+
19+
for(int[] xy: new int[][]{{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}}){
20+
21+
int _x = xy[0];
22+
int _y = xy[1];
23+
24+
if(allowed(_x, _y, mx, my, grid, visited)){
25+
travel(_x, _y, mx, my, grid, visited);
26+
}
27+
}
28+
29+
}
30+
31+
public int numIslands(char[][] grid) {
32+
33+
final int mx = grid.length;
34+
if(mx == 0) return 0;
35+
final int my = grid[0].length;
36+
37+
int count = 0;
38+
boolean[][] visited = new boolean[mx][my];
39+
40+
for(int x = 0; x < mx; x++){
41+
for(int y = 0; y < my; y++){
42+
if(allowed(x, y, mx, my, grid, visited)){
43+
44+
travel(x, y, mx, my, grid, visited);
45+
46+
count++;
47+
}
48+
}
49+
}
50+
51+
return count;
52+
}
53+
}

number-of-islands/index.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
layout: solution
3+
title: Number of Islands
4+
date: 2015-04-08 13:28:15+08:00
5+
leetcode_id: 200
6+
---
7+
{% assign leetcode_name = {{page.path | remove: '/index.md'}} %}
8+
{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %}
9+
{% include {{leetcode_readme}} %}

0 commit comments

Comments
 (0)