OPENJUDGE 2815 城堡问题
算法思想:
利用DFS搜索遍历整个空间。
注意事项:
1)DON'T USE MEMSET FUNCTION TO INITIALIZE THE MATRIX!!
2)TAG FOR VISIT INFO ARE REQUIRED
//SOURCE CODE
# include <iostream>
# include <cmath>
# include <cstring>
# include <memory>
# define UNVISITED 0
# define VISITED 1
using namespace std;
int currentMax = 0;
class Mat{
private:
int ** mStorage;
bool ** tagVisited;
int m; //Lines
int n; //Columns
int rooms;
int maxArea;
public:
Mat(const int m_, const int n_)
{
int b = 0;
mStorage = new int*[m_+2];
tagVisited = new bool* [m_+2];
for ( int i = 0; i < m_+2; i++ )
{
mStorage[i] = new int[n_+2];
tagVisited[i] = new bool[n_+2];
}
for ( int a = 0; a < m_+2; a++ )
{
for ( b = 0; b < n_+2; b++ )
{
mStorage[a][b] = 0;
tagVisited[a][b] = false;
}
}
//memset(tagVisited,false,sizeof(tagVisited)); WTF??WHY CAN'T USE THIS STUFF???????
for ( int j = 0; j < n_+2; j++ )
{
mStorage[0][j] = 15;
mStorage[m_+1][j] = 15;
tagVisited[0][j] = true;
tagVisited[m_+1][j] = true;
}
for ( int k = 0; k < m_+2; k++ )
{
mStorage[k][0] = 15;
mStorage[k][n_+1] = 15;
tagVisited[k][0] = true;
tagVisited[k][n_+1] = true;
}
m = m_;
n = n_;
rooms = 0;
maxArea = 0;
}
void getMatrix()
{
int j = 1;
for ( int i = 1; i <= m ; i++ )
{
for ( j = 1; j <= n; j++ )
{
cin >> mStorage[i][j];
}
}
}
void DFS(int a, int b)
{
if ( tagVisited[a][b] == false )
{
tagVisited[a][b] = true;
//Add Something to Calculate Area
currentMax++;
if ( (mStorage[a][b] & 0x00000004) == 0 )
{
DFS(a,b+1);
}
if ( (mStorage[a][b] & 0x00000008) == 0 )
{
DFS(a+1,b);
}
if ( (mStorage[a][b] & 0x00000001) == 0 )
{
DFS(a,b-1);
}
if ( (mStorage[a][b] & 0x00000002) == 0 )
{
DFS(a-1,b);
}
}
}
void updateMaxArea()
{
if ( currentMax > maxArea )
{
maxArea = currentMax;
}
}
void traverse()
{
int count = 0;
int j = 1;
for ( int i = 1; i <= m; i++ )
{
for ( j = 1; j <= n; j++ )
{
currentMax = 0;
if ( tagVisited[i][j] == false )
{
DFS(i,j);
count++;
updateMaxArea();
}
}
}
rooms = count;
}
void printInfo()
{
cout << rooms << endl;
cout << maxArea << endl;
}
};
int main()
{
int M = 0;
int N = 0;
cin >> M >> N;
Mat castelle(M,N);
castelle.getMatrix();
castelle.traverse();
castelle.printInfo();
return 0;
}