在H * W的地图上有N个奶酪工厂,每个工厂分别生产硬度为1-N的奶酪。有一只老鼠准备从出发点吃遍每一个工厂的奶酪。老鼠有一个体力值,初始时为1,每吃一个工厂的奶酪体力值增加1(每个工厂只能吃一次),且老鼠只能吃硬度不大于当前体力值的奶酪。 老鼠从当前格到上下左右相邻的无障碍物的格需要时间1单位,有障碍物的格不能走。走到工厂上时即可吃到该工厂的奶酪,吃奶酪时间不计。问吃遍所有奶酪最少用时
入出力例
输入:第一行三个整数H(1 <= H <= 1000)、W(1 <= W <=1000)、N(1 <= N <= 9),之后H行W列为地图, “.“为空地, ”X“为障碍物,”S“为老鼠洞,N表示有N个生产奶酪的工厂,硬度为1-N。
#include <iostream>
#include <queue>
#include <string>
#include <cstdio>
#include <cstring>
#include <utility>
using namespace std;
typedef pair<int, int> P;
char maze[1005][1005];
int d[1005][1005];
int step[4][2]= {1,0,0,1,-1,0,0,-1};
int h, w, n, hard;
int si, sj;
const int INF = 0x3f3f3f3f;
int tot = 0;
void BFS(int ai, int aj)
{
queue<P> que;
for(int i = 0; i < h; i++)
{
for(int j = 0; j < w; j++)
{
d[i][j] = INF;
}
}
que.push(P(ai, aj));
d[ai][aj] = 0;
while(!que.empty())
{
P a = que.front();
que.pop();
int x = a.first, y = a.second;
if(maze[x][y]-'0' == hard)
{
tot += d[x][y];
si = x;
sj = y;
break;
}
for(int i = 0; i < 4; i++)
{
int dx = x+step[i][0];
int dy = y+step[i][1];
if(dx>=0 && dx<h && dy>=0 && dy<w && maze[dx][dy]!='X' && d[dx][dy]==INF)
{
d[dx][dy] = d[x][y]+1;
que.push(P(dx, dy));
}
}
}
}
int main()
{
while(scanf("%d%d%d", &h, &w, &n) != EOF)
{
for(int i = 0; i < h; i++)
{
for(int j = 0; j < w; j++)
{
cin>>maze[i][j];
if(maze[i][j] == 'S')
{
si = i;
sj = j;
}
}
}
tot = 0;
hard = 1;
for(int i = 0; i < n; i++)
{
BFS(si, sj);
hard++;
}
cout << tot << endl;
}
return 0;
}