1 条题解

  • 0
    @ 2025-8-8 8:59:28
    • 下面的代码哪里不对呢?
    • 试一试这组数据
    4 4
    #.##
    #A##
    ##A@
    ##=#
    
    • 下面的代码会输出什么答案呢?
    #include <bits/stdc++.h>
    using namespace std;
    int n , m , sx = -1 , sy = -1 , ex = -1 , ey = -1 , dis[305][305] , tx[26][2] , ty[26][2] , tcnt[26];
    char a[305][305];
    const int dx[] = {-1 , 0 , 0 , 1} , dy[] = {0 , -1 , 1 , 0};
    void bfs(){
    	memset(dis , -1 , sizeof(dis));
    	queue<int> qx , qy;
    	dis[sx][sy] = 0;
    	qx.push(sx) , qy.push(sy);
    	while(!qx.empty()){
    		int x = qx.front() , y = qy.front();
    		qx.pop() , qy.pop();
    		if(x == ex && y == ey) return;
    		if(a[x][y] >= 'A' && a[x][y] <= 'Z'){
    			int t = a[x][y] - 'A' , nx , ny;
    			if(tx[t][0] == x && ty[t][0] == y) nx = tx[t][1] , ny = ty[t][1];
    			else nx = tx[t][0] , ny = ty[t][0];
    			if(dis[nx][ny] == -1){
    				dis[nx][ny] = dis[x][y];
    				qx.push(nx) , qy.push(ny);
    				x = nx , y = ny;
    			}
    		}
    		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 && a[nx][ny] != '#'){
    				if(dis[nx][ny] == -1){
    					dis[nx][ny] = dis[x][y] + 1;
    					qx.push(nx) , qy.push(ny);
    				}
    			}
    		}
    	}
    }
    int main(){
    	cin >> n >> m;
    	for(int i = 0 ; i < n ; i++){
    		for(int j = 0 ;j < m ; j++){
    			cin >> a[i][j];
    			if(a[i][j] == '@') sx = i , sy = j;
    			else if(a[i][j] == '=') ex = i , ey = j;
    			else if(a[i][j] >= 'A' && a[i][j] <= 'Z'){
    				int x = a[i][j] - 'A';
    				tx[x][tcnt[x]] = i , ty[x][tcnt[x]] = j;
    				tcnt[x]++;
    			}
    		}
    	}
    	bfs();
    	cout << dis[ex][ey];
    }
    
    • 1

    信息

    ID
    65
    时间
    1000ms
    内存
    512MiB
    难度
    9
    标签
    递交数
    141
    已通过
    15
    上传者