题目描述给了很多坑爹的条件,其实是要想清楚一点就好办了:如果点(i, j)的人能够拦截到你,那他完全可以到终点等着你。。。所以就只需求出每个点到终点的最短路,ans就是所有到终点距离小于等于你到终点的距离的点的人数和。
从终点开始做bfs,记录每个点的距离,ans每次加上当前点的人数值,在遍历到起始点的时候终止bfs就OK了。
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cstdio>
#include<cstring>
#include<cmath>
#define FF(i, a, b) for(int i=a; i<b; i++)
#define FD(i, a, b) for(int i=a; i>b; i--)
#define REP(i, n) for(int i=0; i<n; i++)
#define CLR(a, b) memset(a, b, sizeof(a))
#define LL long long
using namespace std;
const int maxn = 1111;
char ch[maxn][maxn];
int n, m, start;
int g[maxn][maxn];
bool vis[maxn][maxn];
struct Point
{
int x, y, step;
}s, t;
bool inside(int x, int y)
{
if(x >= 0 && x < n && y >= 0 && y < m )
return 1;
return 0;
}
int dx[4]={0, 0, 1, -1};
int dy[4]={1, -1, 0, 0};
int bfs()
{
int ret = 0, cnt = 1000000;
t.step = 0;
queue<Point> q;
q.push(t);
while(!q.empty())
{
Point k = q.front(), tmp; q.pop();
if(k.step > cnt) break;
ret += g[k.x][k.y];
REP(i, 4)
{
tmp.x = k.x + dx[i], tmp.y = k.y + dy[i];
if(inside(tmp.x, tmp.y) && ch[tmp.x][tmp.y] != 'T' && !vis[tmp.x][tmp.y])
{
if(tmp.x == s.x && tmp.y == s.y) cnt = k.step+1;
tmp.step = k.step+1;
q.push(tmp);
vis[tmp.x][tmp.y] = 1;
}
}
}
return ret;
}
int main()
{
while(cin>>n>>m)
{
CLR(vis, 0);
REP(i, n)
{
cin>>ch[i];
REP(j, m)
{
if(ch[i][j] == 'S') s.x = i, s.y = j, g[i][j] = 0;
else if(ch[i][j] == 'E') t.x = i, t.y = j, g[i][j] = 0;
else if(ch[i][j] == 'T') g[i][j] = 0;
else g[i][j] = ch[i][j] - '0';
}
}
cout<<bfs()<<endl;
}
return 0;
}