【题意】:给出一个矩阵n*m,每个元素为0或1,对于每一个位置,以其为起点往外走,只能平行于坐标轴走,两个点的距离表示两点间包含1最少的路径上1的个数,一个位置的代价表示它到其他所有点的距离中最大的距离,求所有位置中最小的代价;
【解题思路】:这题其实就是求两个点之间的最短路,所以可以直接dijkstra去做,将点上的0或1表示成两点之间的距离,即边,然后枚举一个起点,求出最短路的最大值就好了。
#include<bits/stdc++.h>
using namespace std;
class GameOnABoard{
struct node{
int x,y,c;
bool operator<(const node & A)const{return c>A.c;}
}nw,nx;
priority_queue<node>Q;
public:
int rx[4]={0,1,0,-1};
int ry[4]={1,0,-1,0};
const int INF=1e9+7;
int G[55][55],cost[55][55],mark[55][55],n,m,ans;
void pre(){
int mx=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
mx=max(cost[i][j],mx),cost[i][j]=INF,mark[i][j]=0;
ans=min(ans,mx);
}bool check(int x,int y){
return 1<=x&&x<=n&&1<=y&&y<=m;
}
int optimalChoice(vector <string> C){
ans=INF;
n=C.size();m=C[0].size();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
G[i][j]=(C[i-1][j-1]=='1'),cost[i][j]=INF;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
cost[i][j]=G[i][j];
Q.push((node){i,j,G[i][j]});
while(!Q.empty()){
nw=Q.top();Q.pop();
int x,y,c=nw.c;
if(mark[nw.x][nw.y]==1)continue;
mark[nw.x][nw.y]=1;
for(int k=0;k<4;k++){
x=nw.x+rx[k];
y=nw.y+ry[k];
if(check(x,y)&&nw.c+G[x][y]<cost[x][y]){
cost[x][y]=nw.c+G[x][y];
Q.push((node){x,y,cost[x][y]});
}
}
}pre();
}return ans;
}
};