A + - + -坦克车只能水平或垂直方向上移动到相邻的区。
- + - - +
- + + + -
+ - + - +
B + - + -
5
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
10
#include<iostream> #include<string> #include<string.h> #include<algorithm> #include<queue> using namespace std; int n,flag=0; int vis[105][105]; char a[105][105]; int dir[4][2]={{1,0},{0,-1},{0,1},{-1,0}};; struct node { int x,y,step; }; int check(int x,int y) { if(x>=0&&x<n&&y>=0&&y<n) return 1; else return 0; } void bfs(int x,int y) { node temp; temp.x=x; temp.y=y; temp.step=0; queue<node>p; p.push(temp); vis[x][y]=1; while(!p.empty()) { node now=p.front(); p.pop(); for(int i=0;i<4;i++) { int tx=now.x+dir[i][0]; int ty=now.y+dir[i][1]; if(check(tx,ty)&&vis[tx][ty]==0&&a[tx][ty]!=a[now.x][now.y]) { if(a[tx][ty]==‘B‘) { cout<<now.step+1<<endl; flag=1; return ; } vis[tx][ty]=1; node temp; temp.x=tx; temp.y=ty; temp.step=now.step+1; p.push(temp); } } } } int main() { cin>>n; int s,e; memset(vis,0,sizeof(vis)); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cin>>a[i][j]; if(a[i][j]==‘A‘) { s=i; e=j; } } } bfs(s,e); if(flag==0) cout<<-1<<endl; return 0; } // 5 // A + - + - // - + - - + // - + + + - // + - + - + // B + - + -
#include<iostream> #include<string.h> #include<algorithm> using namespace std; int n,flag=0,mn=99999999; int vis[105][105],dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}}; char a[105][105]; int check(int x,int y) { if(x>=0&&x<n&&y>=0&&y<n) return 1; else { return 0; } } void dfs(int x,int y,int cnt) { if(mn<=cnt)//优化避免超时 return ; if(a[x][y]==‘B‘) { flag=1; mn=min(mn,cnt); return ; } else { for(int i=0;i<4;i++) { int tx=x+dir[i][0]; int ty=y+dir[i][1]; if(check(tx,ty)&&vis[tx][ty]==0&&a[x][y]!=a[tx][ty]) { vis[tx][ty]=1; dfs(tx,ty,cnt+1); vis[tx][ty]=0; } } } } int main() { cin>>n; int x,y; memset(vis,0,sizeof(vis)); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cin>>a[i][j]; if(a[i][j]==‘A‘) { x=i; y=j; } } } vis[x][y]=1; dfs(x,y,0); if(flag==0) cout<<-1<<endl; else cout<<mn<<endl; //system("pause"); return 0; }
原文:https://www.cnblogs.com/-citywall123/p/12305112.html