题目
思路
呵呵,正解并不是什么神奇的方法
而是最原始的最粗暴的最有用的最万能的————搜索
依题模拟即可
(Code)
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 35;
int n , m , mp[N][N] , vis[N][N] , ans , up;
char s[N];
void dfs(int x , int y , int s , int num)
{
if (s >= ans) return;
if (num == up){ans = s; return;}
vis[x][y] = 1;
int l , r;
l = x , r = y;
while (r + 1 <= m && !mp[l][r + 1] && !vis[l][r + 1]) vis[l][++r] = 1;
if (r != y)
{
dfs(l , r , s + 1 , num + r - y);
for(register int i = y + 1; i <= r; i++) vis[x][i] = 0;
}
l = x , r = y;
while (r - 1 > 0 && !mp[l][r - 1] && !vis[l][r - 1]) vis[l][--r] = 1;
if (r != y)
{
dfs(l , r , s + 1 , num + y - r);
for(register int i = r; i < y; i++) vis[x][i] = 0;
}
l = x , r = y;
while (l + 1 <= n && !mp[l + 1][r] && !vis[l + 1][r]) vis[++l][r] = 1;
if (l != x)
{
dfs(l , r , s + 1 , num + l - x);
for(register int i = x + 1; i <= l; i++) vis[i][y] = 0;
}
l = x , r = y;
while (l - 1 > 0 && !mp[l - 1][r] && !vis[l - 1][r]) vis[--l][r] = 1;
if (l != x)
{
dfs(l , r , s + 1 , num + x - l);
for(register int i = l; i < x; i++) vis[i][y] = 0;
}
vis[x][y] = 0;
}
int main()
{
freopen("game.in" , "r" , stdin);
freopen("game.out" , "w" , stdout);
scanf("%d%d" , &n , &m);
up = n * m;
for(register int i = 1; i <= n; i++)
{
scanf("%s" , s);
for(register int j = 0; j < m; j++)
if (s[j] == '*') mp[i][j + 1] = 1 , --up;
}
ans = 2147483647;
for(register int i = 1; i <= n; i++)
for(register int j = 1; j <= m; j++)
if (!mp[i][j])
{
memset(vis , 0 , sizeof vis);
dfs(i , j , 0 , 1);
}
printf("%d" , ans == 2147483647 ? -1 : ans);
}