題目描述:
跑圖是RPG遊戲中很煩躁的事情。玩家需要跑到距離他最近的傳送點的位置。現在給你一張N \times MN×M的方格圖,每個方格中數值00表示爲平地,數值11表示爲傳送點,你的任務是輸出一張N \times MN×M的矩陣,x y表示從(x,y)(x,y)到距離它最近的傳送點的距離。 這裏的距離是曼哈頓距離,(x1,y1)→(x2,y2) 的距離爲|x1-x2|+|y1-y2|∣x1 −x2∣+∣y1−y2∣。
輸入:
第一行,有兩個數n,m。接下來n行,每行m個數。
數據保證至少有一個傳送點。
1 =< n <= 500 ,1≤ n ≤500,
輸出:
n行,每行m個數,表示某個點到離它最近的傳送點的距離。
樣例輸入
2 3
0 0 0
1 0 1
樣例輸出
1 2 1
0 1 0
代碼如下:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
typedef pair<int,int> P;
int d[505][505];
int arr[505][505];
int vis[505][505];
int m,n;
P st;
int dx[][2]={1,0,-1,0,0,1,0,-1};
queue<P>q;
void bfs()
{
while(!q.empty())
{
P tp=q.front();
q.pop();
vis[tp.first][tp.second]=1;
for(int i=0;i<4;i++)
{
int xx=tp.first+dx[i][0];
int yy=tp.second+dx[i][1];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&!vis[xx][yy]&&arr[xx][yy]!=1)
{
vis[xx][yy]=1;
q.push(P(xx,yy));
d[xx][yy]=d[tp.first][tp.second]+1;
}
}
}
}
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%d",&arr[i][j]);
if(arr[i][j]==1)
{
q.push(P(i,j));
}
}
}
bfs();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(j < m - 1)
cout<<d[i][j]<<" ";
else cout << d[i][j];
}
cout<<endl;
}
return 0;
}