10 条题解

  • 1
    @ 2026-10-11 15:30:11
    #include<bits/stdc++.h>
    using namespace std;
    struct node
    {
    	int x,y,d;
    };
    char m[205][205];
    bool vis[205][205];
    int l,h;
    int dx[] = {2,2,-2,-2,1,1,-1,-1};
    int dy[] = {1,-1,1,-1,2,-2,2,-2};
    bool cheak(int x,int y)
    {
    	return x >= 1 && x <= h && y <= l && y >= 1 && m[x][y] != '*' && !vis[x][y];  
    }
    int bfs(int x,int y)
    {
    	queue<node> q;
    	q.push({x,y,0});
    	vis[x][y] = 1;
    	while(!q.empty())
    	{
    		node p;
    		p=q.front();
    		q.pop();
    		if(m[p.x][p.y] == 'H')
    		{
    			return p.d;
    		}
    		for(int i = 0 ; i < 8 ; i++)
    		{
    			int nx = p.x + dx[i];
    			int ny = p.y + dy[i];
    			if(cheak(nx,ny))
    			{
    				q.push({nx,ny,p.d + 1});
    				vis[nx][ny] = 1;
    			}
    		}
    	}
     } 
    int main()
    {
    	cin >> l >> h;
    	for(int i = 1 ; i <= h ; i++)
    	{
    		for(int j = 1 ; j <= l ; j++)
    		{
    			cin >> m[i][j];
    		}
    	}
    	for(int i = 1 ; i <= h ; i++)
    	{
    		for(int j = 1 ; j <= l ; j++)
    		{
    			if(m[i][j] == 'K')
    			{
    				cout << bfs(i,j);
    			}
    		 } 
    	}
    }
    

    信息

    ID
    99
    时间
    1000ms
    内存
    128MiB
    难度
    5
    标签
    递交数
    505
    已通过
    193
    上传者