题目链接
题意:
现在有一个电路矩阵图,矩阵上的每个格子都是有一条导线,这个导线会连接左上角和右下角或者是连接左下角和右上角。每一次操作会将某个格子的导线方向换一下,现在问你最少需要换多少次才能使(0,0)和(n,m)联通,比如说下面这幅图只需要换第二幅图的红线的格子就可以联通,那么答案就是1。
分析:
首先如果n+m不是偶数的话一定不连通,因为起点的横纵坐标之和是偶数,所以每次电流的走都是横纵坐标增量和是偶数,那么就行了,首先特判一下,然后进行bfs,将每个格子不和原来走向一样的格子置成边权为1,相同则置成边权为0,然后进行广搜就行,因为这个是求的最小值,那么可以用双端队列来维护这个性质,因为这个题的队列有两个性质,即两端性和单调性,使用双端队列之后也满足这个性质,证明完毕后就是看一些细节了,就是看当前走到了哪个节点和那个格子的坐标差,相信聪明的读者一看就看出来了呀,那么现在来看一下代码吧:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<deque>
using namespace std;
const int N = 510,M = N*N;
typedef pair<int,int> PII;
int dis[N][N],n,m;
char g[N][N];
bool st[N][N];
int bfs(){
int dx[4] = {-1,-1,1,1},dy[4] = {-1,1,1,-1};
int ix[4] = {-1,-1,0,0},iy[4] = {-1,0,0,-1};
memset(st,0,sizeof st);memset(dis,0x3f,sizeof dis);
dis[0][0] = 0;
deque<PII> q;
q.push_back({0,0});
char cs[6] = "\\/\\/";
while(q.size()){
auto t = q.front();
q.pop_front();
int x = t.first , y = t.second;
if(st[x][y]) continue;
st[x][y] = true;
for(int i=0;i<4;i++){
int nx = x + dx[i],ny = y + dy[i];
if(nx < 0 || nx > n || ny < 0 || ny > m) continue;
int ga = x + ix[i],gb = y + iy[i];
int d = (g[ga][gb] != cs[i]);
if(dis[nx][ny] > dis[x][y] + d){
dis[nx][ny] = dis[x][y] + d;
if(d) q.push_back({nx,ny});
else q.push_front({nx,ny});
}
}
}
return dis[n][m];
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) scanf("%s",g[i]);
if((n + m) & 1) puts("NO SOLUTION");
else printf("%d\n",bfs());
}
return 0;
}