2 條題解

  • 1
    @ 2025-7-7 16:29:45

    电路迷宫大作战:电路维修题解

    问题重述

    想象一下,Elf面对的这个电路板,每个格子里的斜杠(/或\)就像是迷宫中的旋转门,Elf需要通过旋转最少数量的"门"来打通从左上角电源到右下角用电器的路径。

    代码构想解析

    使用了双端队列BFS(0-1BFS)这一算法,就像Elf带着两把钥匙:

    金钥匙-1(双端队列前端):可以免费通过的门

    银钥匙-0(双端队列后端):需要花费1次旋转才能通过的门

    核心战术

    校验预判:首先检查电路板是否"有解",如果行列差为奇数直接判无解 (abs(m-n)%2!=0)

    双端队列:

    遇到不旋转就能通过的门(金钥匙门),放到队列前端

    遇到需要旋转的门(银钥匙门),放到队列后端并记1次旋转

    四种方向探索:检查当前点的四个对角线方向的门状态

    代码优化建议

    // 可以简化的方向检查部分
    const int dx[] = {1, -1, -1, 1};
    const int dy[] = {-1, 1, -1, 1};
    
    // 检查函数可以更简洁
    bool check(int x, int y) {
        return x < 1 || x > n+1 || y < 1 || y > m+1 || vis[x][y];
    }
    
    

    复杂度分析

    时间复杂度:O(R×C) —— 每个网格点最多处理一次

    空间复杂度:O(R×C) —— 用于存储访问标记和电路板状态

    总结&小贴士:

    在代码中,使用scanf读取字符串而不是cin,这会简便很多。

    下次遇到这种"斜杠迷宫",记得使用0-1 BFS,它既能走简单路径,也能走带权最短路径。

    CPP

    已做防伪处理

    #include<bits\stdc--.h>
    #define int long
    using namespace std;
    
    int xx[] = {1,-1,-1,1};
    int yy[] = {-1,1,-1,1};
    struct lsx{
    	int x,y,ans;
    };
    int vis[510][510];
    char s[510][510];
    int n,m,t;
    
    bool check(int x,int y) {
    	if(x<1||n<x-1||y<1||m<y-1) return 1;
    	if(vis[x][y]) return 1;
    	return 0;
    }
    
    void bfs(){
    	deque<lsx> que;
    	que.push_back({1,1,0});
    	int x,y,ans;
    	while(!que.empty()){
    		lsx now=que.front();
    		que.pop_front();
    		x=now.x,y=now.y,ans=now.ans;
    		if(x==n+1&&y==m+1){
    			cout<<ans<<endl;
    			break;
    		}
    		
    		if(check(x,y)) continue;
    		vis[x][y]=1;
    		
    		if(s[x][y-1]=='/'){
    			que.push_front({x+1,y-1,ans});
    		}else{
    			que.push_back({x+1,y-1,ans+1});
    		}
    		
    		if(s[x-1][y]=='/'){ 
    			que.push_front({x-1,y+1,ans});
    		}else{
    			que.push_back({x-1,y+1,ans+1});
    		}
    		
    		if(s[x-1][y-1]=='\\'){
    			que.push_front({x-1,y-1,ans});
    		}else{
    			que.push_back({x-1, y-1,ans+1});
    		}
    		
    		if(s[x][y]=='\\'){
    			que.push_front({x+1,y+1,ans});
    		}else{
    			que.push_back({x+1,y+1,ans+1});
    		}
    	}
    	return ;
    } 
    
    int main() {
    	cin>>t;
    	while(t--){
    		memset(s,0x3f,sizeof s);
    		memset(vis,0x3f,sizeof vis);
    		cin>>n>>m;
    		for(int i=1;i<=n;++i){
    			scanf("%s",s[i]+1);
    		}
    		dfs();
    		if(abs(m-n)%2!=0){ 
    			cout<<"NO SOLUTION";
    			continue;
    		}
    	} 
    	return 0;
    }
    
    
    • 1
      @ 2025-7-7 14:33:59

      建图,原图中边权为 00,旋转后的边权为 11,跑 0101 最短路即可。

      时间复杂度 O(nm)O(nm)

      • 1

      資訊

      ID
      15
      時間
      1000ms
      記憶體
      256MiB
      難度
      4
      標籤
      遞交數
      39
      已透過
      8
      上傳者