题意:给你一个n*n的格子,其中-1代表起点,-2代表终点,其他的都代表权值,现在问你从起点到终点的最小权值是多少。
思路:广搜,我们的vis里面存的是你在 (i,j)这个点的权值,之后在我们广搜的时候,我们松弛一下就好了
#include <bits/stdc++.h>
using namespace std;
int sx,sy,ex,ey;
struct node
{
int x,y;
};
int vis[111][1111],a[111][111];
int dir[4][2] = {1,0,-1,0,0,1,0,-1};
int n;
int judge(int x,int y)
{
if(x < 0 || y <0 || x>=n || y >=n)
{
return 0;
}
return 1;
}
void bfs()
{
node now,nex;
now.x = sx,now.y = sy;
queue<node>que;
que.push(now);
vis[sx][sy] = 0;
while(!que.empty())
{
now = que.front();
que.pop();
for(int i = 0 ;i < 4 ; i++)
{
nex.x = now.x + dir[i][0];
nex.y = now.y + dir[i][1];
if(judge(nex.x,nex.y))
{
if(vis[nex.x][nex.y] > vis[now.x][now.y] + a[nex.x][nex.y]){
vis[nex.x][nex.y] = vis[now.x][now.y] + a[nex.x][nex.y];
que.push(nex);
}
}
}
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(vis,9999999,sizeof(vis));
for(int i = 0 ; i < n ;i++)
{
for(int j = 0 ; j < n ; j++)
{
scanf("%d",&a[i][j]);
if(a[i][j] == -1)
{
sx = i;
sy = j;
a[i][j] = 0;
}
if(a[i][j] == -2)
{
ex = i ,ey = j;
a[i][j] = 0;
}
}
}
bfs();
printf("%d\n",vis[ex][ey]);
}
}
/*
5
6 6 0 -2 3
4 2 1 2 1
2 2 8 9 7
8 1 2 1 -1
9 7 2 1 2
*/