This is an easy problem from uva judge http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=812
A really easy problem using DFS. Flood fill.
How I did it
- Read the number of cases
- Read the element rows of the matrix.
- If I found the number 1, I set the dfs_matriz with -1.
- Traverse all the graph.
- If I found a unvisited node, I call dfs and increase the area size.
- Get the max area size.
- After the graph traversal print the max area
Hints
- Print a blank line between cases.
- The last case has not a blank line after having processed. If(cases != 0) print a blank line.
Critical Input
5
11000
01100
00101
10001
01011
11000
01100
00101
10001
01011
0000000000
0000000000
0000000000
0000000000
0000000000
1
11010
01100
00101
10001
01011
Critical Output
5
5
0
1
6
Code
#include <iostream>
#include <algorithm>
#include <cstdio>
#define DFS_WHITE -1
#define DFS_BLACK 1
#define NODES 26
using namespace std;
int dfs_matriz[NODES][NODES];
char matriz[NODES][NODES];
int row, col, area;
void dfs(int x, int y)
{ //cout<<"A>>"<<area<<endl;
dfs_matriz[x][y] = DFS_BLACK;
int a=x, b=y;
if(a-1 >= 0)
{
if(dfs_matriz[a-1][b] == DFS_WHITE)
{
area++;
dfs(a-1, b);
}
if(b+1 < col && dfs_matriz[a-1][b+1] == DFS_WHITE)
{
area++;
dfs(a-1, b+1);
}
if(b-1 >= 0 && dfs_matriz[a-1][b-1] == DFS_WHITE)
{
area++;
dfs(a-1, b-1);
}
}
if(a+1 < row)
{
if(b+1 < col && dfs_matriz[a+1][b+1] == DFS_WHITE)
{
area++;
dfs(a+1, b+1);
}
if(b-1 >= 0 && dfs_matriz[a+1][b-1] == DFS_WHITE)
{
area++;
dfs(a+1, b-1);
}
if(dfs_matriz[a+1][b] == DFS_WHITE)
{
area++;
dfs(a+1, b);
}
}
if(b-1 >= 0 && dfs_matriz[a][b-1] == DFS_WHITE)
{
area++;
dfs(a,b-1);
}
if(b+1 < col && dfs_matriz[a][b+1] == DFS_WHITE)
{
dfs(a,b+1);
area++;
}
}
void readGraph()
{
string str, data = "";
row = 0;
while(getline(cin,str))
{
if(str.size() == 0)
break;
else
{
data += str;
col = str.size();
row++;
}
}
int index = 0;
for(int x=0; x<row; x++)
for(int y=0; y<col; y++, index++)
{
matriz[x][y] = data[index];
if(matriz[x][y] == '1')
dfs_matriz[x][y] = DFS_WHITE;
else
dfs_matriz[x][y] = 0;
}
}
void initGraph()
{
for(int x=0; x<row; x++)
for(int y=0; y<col; y++)
if(matriz[x][y] == '1')
dfs_matriz[x][y] = DFS_WHITE;
}
void print()
{
for(int x=0; x<row; x++)
{ for(int y=0; y<col; y++)
{
cout<<matriz[x][y];
}
cout<<endl;
}
cout<<endl<<"DFS\n";
for(int x=0; x<row; x++)
{ for(int y=0; y<col; y++)
{
cout<<dfs_matriz[x][y];
}
cout<<endl;
}
cout<<endl;
}
int main()
{
string str;
int casos, maxi;
scanf("%d", &casos);
getline(cin,str);//trash
getline(cin,str);//trashwhile(casos--)
{
readGraph();
//print();
maxi = area = 0;
for(int x=0; x<row; x++)
for(int y=0; y<col; y++)
if(dfs_matriz[x][y] == DFS_WHITE)
{
dfs(x,y);
area++;
maxi = max(maxi, area);
area = 0;
}
initGraph();
if(maxi == 0)
printf("0\n");
else
printf("%d\n", maxi);
if(casos)
printf("\n");
}
return 0;
}