-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbetter_islands.js
More file actions
54 lines (37 loc) · 967 Bytes
/
better_islands.js
File metadata and controls
54 lines (37 loc) · 967 Bytes
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
(function(){
'use strict';
var test = [[1,1,0,0,0],
[0,1,0,0,1],
[1,1,0,0,1],
[0,0,1,0,0],
[0,1,0,0,0]];
function islands(matrix){
let count = 0;
for (let yCoor = 0; yCoor < matrix.length; yCoor++){
for (let xCoor = 0; xCoor < matrix[yCoor].length; xCoor++){
if (matrix[yCoor][xCoor] === 1){
count++;
traverse(xCoor, yCoor);
}
}
}
function traverse(x, y){
if (x < 0 || y < 0 || x >= matrix[0].length || y >= matrix.length){
return;
} else if (matrix[y][x] === 0){
return;
}
// By turning each land (1) into water (0), as I
// encounter it, I don't have to worry about double-
// counting land masses as I iterate to new coordinates
matrix[y][x] = 0;
traverse(x+1, y);
traverse(x-1, y);
traverse(x, y+1);
traverse(x, y-1);
}
return count;
}
console.log(islands(test));
console.log('hello!');
})()