分享一个很好写的做法。
Solution
考虑建图跑最短路。
钦定一个网格拥有两条边:右边的边,下面的边。将右边的边记为 ,下面的边记为 。即 表示网格 右边的边, 表示网格 下面的边。
假设当前网格为 。
对于类型 A:
- 从左到右,建边:,从右到左就是反向边;
- 从上到下,建边:,从下到上就是反向边。
同理,对于类型 B:
- 从左到下,建边:,从下到左就是反向边;
- 从上到右,建边:,从右到上就是反向边。
对于类型 C:
- 从左到上,建边:,从上到左就是反向边;
- 从下到右,建边:,从右到下就是反向边。
上述建边的边权为:若走法为类型 A,但网格 不为字符A,那么边权为 ,否则边权为 。其他类型同理。
连完边就可以跑最短路了。记左上角网格的坐标为 ,右下角网格的坐标为 :
- 起点为 ,即网格 左边的网格 的右边的边。
- 终点为 ,即网格 右边的边。
最短路直接拖的 Dijkstra 板子,所以复杂度为 。
写法上,可以将每个网格进行标号,方便计算节点编号。具体可以参考代码,很好写。
Code
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
const ll LLINF=0x3f3f3f3f3f3f3f3fLL;
const int MAX=8e5+10;
struct Dijkstra
{
#define type int
const type inf=INF;
struct node
{
int id;
type v;
friend bool operator <(node a,node b){return a.v>b.v;}
};
static const int N=MAX;
vector<node> mp[N];
type dis[N];
int n,vis[N];
void init(int _n)
{
n=_n;
for(int i=0;i<=n;i++) mp[i].clear();
}
void add_edge(int x,int y,type v){mp[x].push_back({y,v});}
void work(int s)
{
int i,to;
type w;
priority_queue<node> q;
for(i=0;i<=n;i++)
{
dis[i]=inf;
vis[i]=0;
}
dis[s]=0;
q.push({s,type(0)});
while(!q.empty())
{
node t=q.top();
q.pop();
if(vis[t.id]) continue;
vis[t.id]=1;// this node has already been extended
for(auto &it:mp[t.id])
{
to=it.id;
w=it.v;
if(dis[to]>dis[t.id]+w)
{
dis[to]=dis[t.id]+w;
if(!vis[to]) q.push({to,dis[to]});
}
}
}
}
#undef type
}dij;
char s[MAX];
void add_edge(int a,int b,int x,
int c,int d,int y,
int w,vector<vector<int>>& id)
{
dij.add_edge(id[a][b]+x,id[c][d]+y,w);
dij.add_edge(id[c][d]+y,id[a][b]+x,w);
}
int main()
{
int T,n,m,i,j,tot;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
vector<vector<int>> id(n+2,vector<int>(m+2,0));
vector<string> mp;
mp.push_back("");
for(i=1;i<=n;i++)
{
scanf("%s",s);
mp.push_back(" "+string(s));
}
tot=1;
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
id[i][j]=tot;
tot+=2;
}
}
dij.init(tot+2);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
// right=0, down=1
add_edge(i,j-1,0,i,j,0,mp[i][j]!='A',id);
add_edge(i-1,j,1,i,j,1,mp[i][j]!='A',id);
add_edge(i,j-1,0,i,j,1,mp[i][j]!='B',id);
add_edge(i-1,j,1,i,j,0,mp[i][j]!='B',id);
add_edge(i,j-1,0,i-1,j,1,mp[i][j]!='C',id);
add_edge(i,j,1,i,j,0,mp[i][j]!='C',id);
}
}
dij.work(id[1][0]+0);
printf("%d\n",dij.dis[id[n][m]+0]);
}
return 0;
}