Skip to content

Commit da8ccbc

Browse files
authored
Merge pull request TheAlgorithms#347 from kgolder92/number-of-islands
Number of islands
2 parents 68d821f + b06aa87 commit da8ccbc

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

Graphs/NumberOfIslands.js

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/* Number of Islands
2+
https://dev.to/rattanakchea/amazons-interview-question-count-island-21h6
3+
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
4+
5+
two a dimensial grid map
6+
each element is going to represent a peice of land
7+
1 is land,
8+
0 is water
9+
output a number which is the number of islands
10+
11+
Example 1:
12+
Input:
13+
11110
14+
11010
15+
11000
16+
00000
17+
18+
Output: 1
19+
20+
Example 2:
21+
Input:
22+
11000
23+
11000
24+
00100
25+
00011
26+
27+
Output: 3
28+
29+
I: two dimensional array
30+
O: a single integer; total number of islands
31+
32+
Pseudocode:
33+
OUTER FUNCTION
34+
set count to 0
35+
36+
INNER FUNCTION - flood (col, row)
37+
if the tile is water
38+
return
39+
make tile water(flood tile)
40+
invoke flood on the neighbor coordinates
41+
42+
iterate over the matrix (col, row)
43+
if the current element is a 1
44+
increment count
45+
invoke flood (coordinates for col and row)
46+
47+
Return the count
48+
*/
49+
const grid = [
50+
['1', '1', '0', '0', '0'],
51+
['1', '1', '0', '0', '0'],
52+
['0', '0', '1', '0', '0'],
53+
['0', '0', '0', '1', '1']
54+
]
55+
56+
const islands = (matrixGrid) => {
57+
const matrix = matrixGrid
58+
let counter = 0
59+
60+
const flood = (row, col) => {
61+
if (row < 0 || col < 0) return // Off the map above or left
62+
if (row >= matrix.length || col >= matrix[row].length) return // Off the map below or right
63+
64+
const tile = matrix[row][col]
65+
if (tile !== '1') return
66+
67+
matrix[row][col] = '0'
68+
69+
flood(row + 1, col) // Down
70+
flood(row - 1, col) // Up
71+
flood(row, col + 1) // Right
72+
flood(row, col - 1) // Left
73+
}
74+
75+
for (let row = 0; row < matrix.length; row += 1) {
76+
for (let col = 0; col < matrix[row].length; col += 1) {
77+
const current = matrix[row][col]
78+
if (current === '1') {
79+
flood(row, col)
80+
counter += 1
81+
}
82+
}
83+
}
84+
return counter
85+
}
86+
console.log(islands(grid))

0 commit comments

Comments
 (0)