-
Notifications
You must be signed in to change notification settings - Fork 0
/
islands.cpp
67 lines (58 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
#include<iostream>
#include<string>
#include<cstdlib>
#include<cstring>
using namespace std;
template<int ROW,int COL>
bool isSafe(int (&M)[ROW][COL],bool (&visited)[ROW][COL],int i,int j)
{
if(i >= 0 && i < ROW && j >=0 && j < COL && M[i][j] && !visited[i][j])
return true;
return false;
}
template<int ROW,int COL>
void DFS(int (&M)[ROW][COL],bool (&visited)[ROW][COL],int i,int j)
{
static int x[] = {-1,1 ,1,-1,0, 0,1,-1};
static int y[] = {-1,1,-1, 1,1,-1,0, 0};
visited[i][j] = true;
for(int k = 0;k < 8; k++)
{
if(isSafe(M,visited,i + x[k], j + y[k]))
{
DFS(M,visited,i + x[k], j + y[k]);
}
}
}
template<int ROW, int COL>
int countIslands(int (&M)[ROW][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] )
{
count++;
DFS(M,visited,i,j);
}
}
}
return count;
}
int main()
{
int M[][5] =
{
{1,1,0,0,0},
{0,1,0,0,1},
{1,0,0,1,1},
{0,0,0,0,0},
{1,0,1,0,1}
};
cout << countIslands(M) << endl;
return 0;
}