-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathflood-fill_dfs.cpp
More file actions
66 lines (50 loc) · 1.64 KB
/
Copy pathflood-fill_dfs.cpp
File metadata and controls
66 lines (50 loc) · 1.64 KB
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
#include <iostream>
#include <vector>
using namespace std;
//SOLUCAO FLOOD-FILL COM DFS PARA O PROBLEMA DO TABULEIRO DESCONEXO
const int MAXN = 1010; // Maior tamanho de uma dimensão do tabuleiro que esperamos ler
int n, m;
int board[MAXN][MAXN]; // board[i][j] = 1, se e somente se a célula (i,j) está quebrada
bool visited[MAXN][MAXN];
bool is_cell_valid(int x, int y)
{
if (x < 0 || x >= n || y < 0 || y >= m)
return false;
if (board[x][y] == 1)
return false;
if (visited[x][y])
return false;
return true;
}
void dfs(int x, int y)
{
visited[x][y] = true;
if (is_cell_valid(x + 1, y)) // Checa se podemos ir para o sul
dfs(x + 1, y);
if (is_cell_valid(x, y + 1)) // Checa se podemos ir para o leste
dfs(x, y + 1);
if (is_cell_valid(x - 1, y)) // Checa se podemos ir para o norte
dfs(x - 1, y);
if (is_cell_valid(x, y - 1)) // Checa se podemos ir para o oeste
dfs(x, y - 1);
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> board[i][j];
int qtd_components = 0;
for (int x = 0; x < n; x++)
{
for (int y = 0; y < m; y++)
{
if (visited[x][y] || board[x][y] == 1) // Checa se já visitamos essa célula anteriormente ou se ela está quebrada
continue;
// Nós achamos uma nova componente
dfs(x, y); // Marca todas as células da mesma componente da célula (x,y)
qtd_components++; // Aumenta a nossa resposta em 1
}
}
cout << "Número de componentes: " << qtd_components << endl;
}