题目大意
给定灯,每盏灯可以照亮本身、上方和右方的位置,有一盏灯可以旋转,问最少几个灯可以照亮‘ .’ 的位置,并且不能照到‘#’的位置。
解题思路
首先预处理出每个灯所能照亮位置的集合。然后枚举特殊位置的灯,和灯旋转的角度。进行然后DP,求出对应的最少灯数。
代码写的比较难看。。。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
typedef long long LL;
const int INF = 0x7fffffff;
const int MOD = 1e9 + 7;
const int N = 300 + 10;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
char G[N][N];
vector< pair<int, int> > need;
int light[16];
int dp[1 << 16];
int n, m, k;
int idx(char c) {
if(c >= 'a' && c <= 'z') return c - 'a';
else return -1;
}
bool check(int x, int y) {
return G[x][y] != '#' && G[x][y] != '#';
}
int solve(int s[]) {
dp[0] = 0;
int limit = (1 << k) - 1;
for(int i = 0; i <= limit; i++) {
if(dp[i] == -1) continue;
for(int j = 0; j < k; j++) {
int cur = (i | s[j]);
if(dp[cur] == -1) dp[cur] = dp[i] + 1;
else dp[cur] = min(dp[cur], dp[i] + 1);
}
}
return dp[limit] == -1 ? INF : dp[limit];
}
int main() {
#ifdef Tally_Ho
freopen("in.txt", "r", stdin);
#endif // Tally_Ho
while(scanf("%d%d", &n, &m) != EOF && n + m) {
k = 0;
memset(G, 0, sizeof(G));
need.clear();
for(int i = 1; i <= n; i++) {
scanf("%s", &G[i][1]);
for(int j = 1; j <= m; j++) {
if(G[i][j] == '.') {
G[i][j] = 'a' + k , k++;
need.push_back(make_pair(i, j));
}
}
}
if(k == 0) {
puts("0");
continue;
}
memset(light, 0, sizeof(light));
for(int i = 0; i < k; i++) {
int x = need[i].first, y = need[i].second;
if(check(x - 1, y) && check(x, y + 1)) {
light[i] = (1 << i);
if(idx(G[x - 1][y]) >= 0) light[i] |= 1 << idx(G[x - 1][y]);
if(idx(G[x][y + 1]) >= 0) light[i] |= 1 << idx(G[x][y + 1]);
} else {
light[i] = 0;
}
}
int ans = INF;
int temp[16];
for(int i = 0; i < k; i++) {
int x = need[i].first, y = need[i].second;
memcpy(temp, light, sizeof(temp));
for(int j = 0; j < 4; j++) {
int sp = 0;
if(j == 0) {
if(check(x - 1, y) && check(x, y + 1)) {
sp = (1 << i);
if(idx(G[x - 1][y]) >= 0) sp |= 1 << idx(G[x - 1][y]);
if(idx(G[x][y + 1]) >= 0) sp |= 1 << idx(G[x][y + 1]);
}
} else if(j == 1) {
if(check(x + 1, y) && check(x, y + 1)) {
sp = (1 << i);
if(idx(G[x + 1][y]) >= 0) sp |= 1 << idx(G[x + 1][y]);
if(idx(G[x][y + 1]) >= 0) sp |= 1 << idx(G[x][y + 1]);
}
} else if( j == 2) {
if(check(x + 1, y) && check(x, y - 1)) {
sp = (1 << i);
if(idx(G[x + 1][y]) >= 0) sp |= 1 << idx(G[x + 1][y]);
if(idx(G[x][y - 1]) >= 0) sp |= 1 << idx(G[x][y - 1]);
}
} else if (j == 3) {
if(check(x - 1, y) && check(x, y - 1)) {
sp = (1 << i);
if(idx(G[x - 1][y]) >= 0) sp |= 1 << idx(G[x - 1][y]);
if(idx(G[x][y - 1]) >= 0) sp |= 1 << idx(G[x][y - 1]);
}
}
memset(dp, -1, sizeof(dp));
temp[i] = sp;
ans = min(ans, solve(temp));
}
}
printf("%d\n", ans == INF ? -1 : ans);
}
return 0;
}