題目:有一個二維的迷宮,墻和格子都是斜著放置的,求裡面最大的獨立區域面積。
分析:圖論、搜索。
如上圖所示,這裡將一個斜著的正方形,分成兩個三角形部分,每個讀入字符的區域分成三個三角形;
這樣可以構成4*row*column個小三角形,每個三角形和三個三角形相鄰;
定義麼個節點有三個link指針,指向相鄰的三個三角形,如果是邊界或者有墻標記成-1;
計算時,先把周圍的掃描一遍,清理掉所有的非封閉區域;
然後,直接dfs即可;
有些做法,將邊看成是有厚度的用2*2的矩陣表示一個圖形搜索;
說明:感覺寫的有點長。
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
string wall[80];
typedef struct _bnode
{
int link[3];
}block;
block Block[100001];
bool Visit[100001];
int dfs(int v)
{
if (v == -1 || true == Visit[v])
return 0;
Visit[v] = true;
int ans = 1;
for (int i = 0; i < 3; ++ i)
ans += dfs(Block[v].link[i]);
return ans;
}
int main()
{
int row, column, cases = 1;
while (cin >> column >> row && row) {
getchar();
for (int i = 0; i < row; ++ i)
getline(cin, wall[i]);
//create graph
for (int i = 0; i < row; ++ i) {
for (int j = 0; j < column; ++ j) {
int u = (i*column+j)*4;
int l = u+1, r = u+2, d = u+3;
if (i != 0)
Block[u].link[0] = d-column*4;
else Block[u].link[0] = -1;
if (wall[i][j] != '/')
Block[u].link[1] = r;
else Block[u].link[1] = -1;
if (wall[i][j] != '\\')
Block[u].link[2] = l;
else Block[u].link[2] = -1;
if (j != 0)
Block[l].link[0] = r-4;
else Block[l].link[0] = -1;
if (wall[i][j] != '/')
Block[l].link[1] = d;
else Block[l].link[1] = -1;
if (wall[i][j] != '\\')
Block[l].link[2] = u;
else Block[l].link[2] = -1;
if (j != column-1)
Block[r].link[0] = l+4;
else Block[r].link[0] = -1;
if (wall[i][j] != '/')
Block[r].link[1] = u;
else Block[r].link[1] = -1;
if (wall[i][j] != '\\')
Block[r].link[2] = d;
else Block[r].link[2] = -1;
if (i != row-1)
Block[d].link[0] = u+column*4;
else Block[d].link[0] = -1;
if (wall[i][j] != '/')
Block[d].link[1] = l;
else Block[d].link[1] = -1;
if (wall[i][j] != '\\')
Block[d].link[2] = r;
else Block[d].link[2] = -1;
}
}
//non enclosed area
memset(Visit, 0, sizeof(Visit));
for (int i = 0; i < row; ++ i) {
for (int j = 0; j < column; ++ j) {
int u = (i*column+j)*4;
int l = u+1, r = u+2, d = u+3;
if (i == 0)
dfs(u);
if (j == 0)
dfs(l);
if (j == column-1)
dfs(r);
if (i == row-1)
dfs(d);
}
}
int max = 0, ans, count = 0;
for (int i = 0; i < row; ++ i) {
for (int j = 0; j < column; ++ j) {
int u = (i*column+j)*4;
int l = u+1, r = u+2, d = u+3;
if (i != 0 && !Visit[u]) {
ans = dfs(u);
if (max < ans)
max = ans;
count += ans>0;
}
if (j != 0 && !Visit[l]) {
ans = dfs(l);
if (max < ans)
max = ans;
count += ans>0;
}
if (j != column-1 && !Visit[r]) {
ans = dfs(r);
if (max < ans)
max = ans;
count += ans>0;
}
if (i != row-1 && !Visit[d]) {
ans = dfs(d);
if (max < ans)
max = ans;
count += ans>0;
}
}
}
printf("Maze #%d:\n",cases ++);
if (count > 0)
printf("%d Cycles; the longest has length %d.\n\n",count,max/2);
else printf("There are no cycles.\n\n");
}
return 0;
}