P1825 [USACO11OPEN]Corn Maze S

#include<bits/stdc++.h>
using namespace std;
const int N = 310;
char s[N][N];
bool st[N][N];
typedef pair<int,int> PII;
#define x first
#define y second
int n,m;
int f[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
int distant[N][N];
int sx,sy;
void check(int &fx,int  &fy)  //引用类型变量 找到队列的 
{  for(int i = 1; i <= n; i ++)
	{ for(int j = 1; j <= m; j ++)
	  {  if(s[i][j] == s[fx][fy] && (i != fx || j != fy) )
	  	 { 
		   fx = i;
	  	   fy = j;
	  	   return;
		 }
	  }
	}
}

int bfs(int x,int y)
{  queue<PII> q;     //定义个队列 
   q.push({x,y});
   st[x][y] = true; 
   distant[x][y] = 0;
   
   while(!q.empty())
   {  auto t = q.front();
           q.pop();
        
        if(s[t.x][t.y] >= 'A' && s[t.x][t.y] <= 'Z') //找到传送装置的起点或者终点 
	    {   int dx,dy;
	        dx = t.x;
	        dy = t.y;
	        check(dx,dy);
	        
	        distant[dx][dy] = distant[t.x][t.y];    //时间赋值给另一个传送门 
	                                                
	        t.x = dx;
	        t.y = dy;
	    }
        if(s[t.x][t.y] == '=') return distant[t.x][t.y];//如果是终点直接返回 
      
	    for(int i = 0; i < 4; i ++)
	     {  int fx = t.x + f[i][0];
	        int fy = t.y + f[i][1];
	        
	        if(fx >= 1 && fx <= n && fy >= 1 && fy <= m && !st[fx][fy] && s[fx][fy] != '#')
	        {   
	            st[fx][fy] = true; 
	            
				distant[fx][fy] = distant[t.x][t.y] + 1;
				
	            q.push({fx,fy});
			}
			
		 }
	  }
   }
   
int main(){
	ios::sync_with_stdio(false); cin.tie(0);cout.tie(0);//读入加速 
	
	cin >> n >> m;
	string s2;
	int x,y;//标记入口点 
	
    for(int i = 1; i <= n; i ++) //读入时顺便找入口,以字符串类型读入 
	{  cin >> s2;
	   for(int j = 1; j <= m; j ++)
	    { s[i][j] = s2[j-1];
	    
	      if(s[i][j] == '@') //入口 
	       { x = i;
	         y = j;
		   }
		   
		}
	}
	
    cout << bfs(x,y) << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值