#include<bits/stdc++.h>
#define int long long
using namespace std;
const int dx[]={0,0,-1,1};
const int dy[]={-1,1,0,0};
int n,m;
int a[105][105];
int ans[105][105];
int sx,sy,ex,ey;
/*
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)
*/
struct node {
int x;
int y;
int t;
};
queue<node> q;
signed main(){
bool flag=false;
cin>>n;
cin>>m;
for(int i=1;i<=m;i++) {
for(int j=1;j<=n;j++) {
char kkk;
cin>>kkk;
if(kkk!='*') a[i][j]=1;
if(kkk=='C' && !flag) sx=i,sy=j,flag=1;
if(kkk=='C' && flag) ex=i,ey=j;
}
}
queue<node> q;
memset(ans,0x3f,sizeof(ans));
q.push(node{sx,sy,0});
ans[sx][sy]=0;
while(!q.empty()){
node now=q.front();
q.pop();
for(int i=0;i<4;i++){
int xx=now.x+dx[i];
int yy=now.y+dy[i];
while(xx>=1 && xx<=m && yy>=1 && yy<=n && ans[xx][yy]>now.t+1 && a[xx][yy]==1){
ans[xx][yy]=now.t+1;
q.push(node{xx,yy,now.t+1});
xx+=dx[i];
yy+=dy[i];
}
}
}
if(ans[ex][ey]!=0x3f) cout<<ans[ex][ey]-1;
else cout<<-1;
return 0;
}
评测结果
)