-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathislands.cpp
71 lines (42 loc) · 1.38 KB
/
islands.cpp
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
#include <iostream>
using namespace std;
#define ROW 5
#define COL 5
int isSafe(int M[][COL], int row, int col,
bool visited[][COL])
{
return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]);
}
void DFS(int M[][COL], int row, int col,
bool visited[][COL])
{
static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
visited[row][col] = true;
for (int k = 0; k < 8; ++k)
if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited))
DFS(M, row + rowNbr[k], col + colNbr[k], visited);
}
int countIslands(int M[][COL])
{
bool visited[ROW][COL];
memset(visited, 0, sizeof(visited));
int count = 0;
for (int i = 0; i < ROW; ++i)
for (int j = 0; j < COL; ++j)
if (M[i][j] && !visited[i][j]) {
DFS(M, i, j, visited);
++count;
}
return count;
}
int main()
{
int M[][COL] = { { 1, 1, 0, 0, 0 },
{ 0, 1, 0, 0, 1 },
{ 1, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 0 },
{ 1, 0, 1, 0, 0 } };
cout << "Number of islands is: " << countIslands(M);
return 0;
}