一個整數,爲最少拆毀的障礙物數量,如果不能逃離廢墟,輸出-1。
Sample Input3 3 3 ### #@* *** 3 4 #### #@.* **.* 3 3 .#. #@# .#.Sample Output
1 0 -1
解題思路:
這道題要求衡量的是拆除障礙物的多少,而不是走的格子數最少,所以結構體定義的時候,要有一個拆除障礙數的記錄,爲了能求出最少的,就使用優先隊列,重載一下運算符,其他的就跟普通的bfs模板題沒有什麼區別
代碼:
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n,m;
char a[105][105];
int vis[105][105];
int dis[][2] = {{1,0},{0,1},{-1,0},{0,-1}};
struct node
{
int x;
int y;
int num;
bool operator < (const node& p)const
{
return num>p.num;
}
};
node beginn;
node endd;
int ok(int aa,int b)
{
if(a[aa][b]!='#'&&aa>=0&&aa<n&&b>=0&&b<m)
return true;
else return false;
}
int bfs(node now)
{
priority_queue<node> q;
q.push(now);
node help;
node help1;
vis[now.x][now.y] = 1;
while(!q.empty())
{
help = q.top();
q.pop();
if(help.x == n-1||help.y == m-1||help.x==0||help.y==0)
return help.num;
for(int i = 0;i<4;i++)
{
help1.x = help.x+dis[i][0];
help1.y = help.y+dis[i][1];
if(ok(help1.x,help1.y))
{
if(a[help1.x][help1.y]=='*')
help1.num = help.num+1;
else help1.num = help.num;
}
if(ok(help1.x,help1.y)&&!vis[help1.x][help1.y])
{
q.push(help1);
vis[help1.x][help1.y] = 1;
}
}
}
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>m;
memset(vis,0,sizeof(vis));
memset(a,0,sizeof(a));
for(int i = 0;i<n;i++)
for(int j = 0;j<m;j++)
{
cin>>a[i][j];
if(a[i][j] == '@')
{
beginn.x = i;
beginn.y = j;
beginn.num = 0;
}
}
int re = bfs(beginn);
cout<<re<<endl;
}
}