题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1033
题意描述:一个N*N的网格状空间(3 <= N <= 33),其中有些格子填充着矩形立柱,其它格子为空,立柱和墙壁需要铺上墙纸(wallpaper),左上角和右下角为入口不用铺设墙纸,而游客不能到达的格子和柱面不用铺设墙纸,求所需墙纸的最小面积; 给定的矩阵由字符串表示,'.'表示空的格子,'#'表示立柱;
思路大致就是DFS,在判断连通和判断是否发现各用一个变量保存,一个格子4条边,相互发现可以减少边数,最后输出计算结果就行了;
需要注意的可能就是,两个入口不一定连通,需要判断是否dfs两次;
AC代码:
//#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
//#include <algorithm>
//#include <queue>
//#include <cmath>
//#include <map>
using namespace std;
vector<vector<bool> >v;
vector<string>g;
int ans = 4, n, cnt = 0;
void dfs(int i, int j){
v[i][j] = true;
cnt++;
if (j + 1 < n&&g[i][j + 1] == '.'){ ans++; if (!v[i][j + 1])dfs(i, j + 1); }
if (i + 1 < n&&g[i + 1][j] == '.'){ ans++; if (!v[i + 1][j])dfs(i + 1, j); }
if (j - 1 >= 0&&g[i][j - 1] == '.'){ ans++; if (!v[i][j - 1])dfs(i, j - 1); }
if (i - 1 >= 0&&g[i - 1][j] == '.'){ ans++; if (!v[i - 1][j])dfs(i - 1, j); }
}
void func(){
cin >> n;
v.resize(n, vector<bool>(n, false));
g.resize(n);
for (int i = 0; i < n; i++)
{
cin >> g[i];
}
dfs(0, 0);
if (v[n - 1][n - 1] == false)dfs(n - 1, n - 1);
cout << (4 * cnt - ans) * 3 * 3 << endl;
}
int main(){
//freopen("out.txt", "w", stdout);
//freopen("in.txt", "r", stdin);
func();
}