-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathislandCount.js
72 lines (61 loc) · 1.53 KB
/
islandCount.js
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
/*
Given a string representation of a 2d map, return the number of islands in the map.
Land spaces are denoted by a zero, while water is denoted by a dot. Two land spaces are
considered connected if they are adjacent (but not diagonal).
Examples:
.0...\n
.00..\n
....0
=> 2
0...0\n
..0..\n
0...0
=> 5
..000.\n
..000.\n
..000.\n
.0....\n
..000.
=> 3
..000.\n
..0...\n
..0.0.\n
..0...\n
..000.
=> 2
*/
function countIslands (mapStr) {
// find x length of map and initialize our counter
var xLength = mapStr.indexOf('\n');
var islandCount = 0;
for (var i = 0; i < mapStr.length; i++) {
if (mapStr[i] === '0') {
// we're looking at land, let's increase our count and recursively
// destroy all of the land connected to this piece
islandCount++;
mapStr = destroyIsland(i, xLength, mapStr);
}
}
return islandCount;
}
function destroyIsland (index, xLength, newMap) {
// newMap[index] is '0', we need to change it to a '.'
newMap = newMap.substr(0, index) + '.' + newMap.substr(index+1);
// destroy land to the right
if (newMap[index+1] === '0') {
newMap = destroyIsland (index+1, xLength, newMap);
}
// destroy land below
if (newMap[index+xLength+1] === '0') {
newMap = destroyIsland (index+xLength+1, xLength, newMap);
}
// destroy land to the left
if (newMap[index-1] === '0') {
newMap = destroyIsland (index-1, xLength, newMap);
}
// destroy land above
if (newMap[index-xLength-1] === '0') {
newMap = destroyIsland (index-xLength-1, xLength, newMap);
}
return newMap;
}