重み付き図BFS
11623 ワード
最短パスをbfsで巡回する場合、通常、優先キュー、すなわち最大または最小の重み値を優先的に考慮する.
メソッド1優先キュー:(関数を内蔵し、より小さな重み値を優先)
方法2:キューに判断条件(配列stepを開き、判断条件step[dx][d y]>step[x][y]+mp[dx][dy])を加える)
転載先:https://www.cnblogs.com/Accepting/p/11273276.html
メソッド1優先キュー:(関数を内蔵し、より小さな重み値を優先)
#include
#include
#include
using namespace std;
struct node{
int x,y,c;
bool friend operator < (node a,node b){
return a.c > b.c;// ( )
}
}r,w;
int n;
int dis[100+10][100+10];
int vis[100+10][100+10];
int ma[100+10][100+10];
int d[4][2]={1,0,0,1,-1,0,0,-1};
void bfs(int xx,int yy){ //bfs
priority_queue q;
r.x = r.y = xx;
r.c = ma[n-1][n-1]; //
dis[n-1][n-1] = ma[n-1][n-1];
vis[n-1][n-1] = 1;
q.push(r);
while(!q.empty()){
r = q.top();
q.pop();
for(int i = 0; i < 4; i++){
int nx = r.x + d[i][0];
int ny = r.y + d[i][1];
if(nx < 0 || ny < 0 || nx >= n || ny >= n || vis[nx][ny]) continue;
w.x = nx;
w.y = ny;
w.c = r.c + ma[nx][ny];// (nx,ny)
vis[nx][ny] = 1;//
q.push(w);
dis[nx][ny]=w.c;// ,
}
}
}
int main(){
cin>>n;
for(int i=0;i< n;i++){
for(int j=0;j< n;j++){
cin>>ma[i][j];
}
}
bfs(n-1,n-1);// (n-1,n-1) ;
for(int i=0;i)
{
cout<<endl;
for(int j=0;j)
printf("%d ",dis[i][j]);
}
return 0;
}
方法2:キューに判断条件(配列stepを開き、判断条件step[dx][d y]>step[x][y]+mp[dx][dy])を加える)
#include
#include
#include
#include
#include
#define INF 100000000
using namespace std;
typedef long long ll;
struct stu{
int a,b;
};
int n;
ll arr[52][52];
ll step[52][52];
ll dp[52][52];
int d[4][2]={1,0,0,1,0,-1,-1,0};
void bfs(int x,int y){
queueque;
que.push({x,y});
step[x][y]=arr[x][y];
while(que.size()){
int xx=que.front().a;
int yy=que.front().b;
que.pop();
for(int i=0;i<4;i++){
int dx=xx+d[i][0];
int dy=yy+d[i][1];
if(dx>=1&&dy>=1&&dx<=n&&dy<=n){
if(step[dx][dy]>step[xx][yy]+arr[dx][dy]){
step[dx][dy]=step[xx][yy]+arr[dx][dy];// step ,
que.push({dx,dy});
}
}
}
}
}
int main(){
while(cin>>n)
{
for(int i=0;i<=50;i++){
for(int j=0;j<=50;j++)
step[i][j]=INF;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>arr[i][j];
}
}
bfs(n,n);
for(int i=1;i<=n;i++){
cout<<endl;
for(int j=1;j<=n;j++)
cout<<step[i][j];// (n,n)
}
}
return 0;
}
:
3
1 2 3
1 2 3
1 2 3
転載先:https://www.cnblogs.com/Accepting/p/11273276.html