-
Notifications
You must be signed in to change notification settings - Fork 0
/
islandCount.js
65 lines (63 loc) · 1.74 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
const islandsCount = (grid, islandCell) => {
var numIslands = 0;
const numRows = grid.length;
const numColumns = grid[0].length;
const visitedCells = new Set();
for (var i = 0; i < numRows; i ++){
for (j = 0; j < numColumns; j ++){
const cell = grid[i][j];
const stringFormat = String([i,j]);
if (cell == islandCell && (!(visitedCells.has(stringFormat)))){
visitedCells.add(stringFormat);
checkNeighbors(grid, i, j, visitedCells, islandCell);
numIslands += 1;
}
}
}
console.log(numIslands)
}
const checkNeighbors = (grid, startingCellRow, startingCellColumn, visitedCells, islandCell) => {
const directions = {
up : [-1, +0],
left : [+0, -1],
down : [+1, +0],
right : [+0, +1]
};
const queue = [[startingCellRow, startingCellColumn]];
while (queue.length > 0){
const toCheck = queue.shift();
const [x,y] = toCheck;
for (let direction in directions){
const [movement_x, movement_y] = directions[direction];
const newx = x + movement_x;
const newy = y + movement_y;
if (newx >= 0 && newx < grid.length && newy >= 0 && newy < grid[0].length && (!(visitedCells.has(String([newx, newy]))))){
const newCell = grid[newx][newy];
if (newCell == islandCell){
queue.push([newx, newy]);
}
visitedCells.add(String([newx, newy]))
}
}
}
return
}
// grid with 4 islands
const grid = [
['W', 'L', 'W', 'L', 'W'],
['W', 'L', 'W', 'W', 'W'],
['W', 'W', 'W', 'L', 'W'],
['W', 'W', 'L', 'L', 'L'],
['L', 'W', 'W', 'L', 'L'],
['L', 'L', 'W', 'W', 'W']
]
// grid with 3 islands
//const grid = [
// ['W', 'L', 'W', 'W', 'W'],
// ['W', 'L', 'W', 'W', 'W'],
// ['W', 'W', 'W', 'L', 'W'],
// ['W', 'W', 'L', 'L', 'L'],
// ['L', 'W', 'W', 'L', 'L'],
// ['L', 'L', 'W', 'W', 'W']
//]
islandsCount(grid, 'L')