8 条题解

  • 0
    @ 2022-4-2 19:59:17
    #include<bits/stdc++.h>
    using namespace std;
    const int N = 155;
    int n, m;
    char str[N][N];
    int dis[N][N];
    int dir[8][2] = {{1, 2}, {2, 1}, {2, -1,}, {-1, 2}, {-2, 1}, {1, -2}, {-2, -1}, {-1, -2}};
    queue<pair<int, int> >q;
    bool cp(int x, int y)
    {
    	if(x < 1 || y < 1 || x > n || y > m || str[x][y] == '*' || dis[x][y] != -1) return false;
    	else return true;
    }
    int bfs(int ex, int ey)
    {
    	while(q.size())
    	{
    		pair<int,int>ad;
    		ad= q.front();
    		q.pop();
    		if(ad.first == ex &&ad.second == ey)
    			return dis[ad.first][ad.second];
    		for(int i = 0; i < 8; i++)
    		{
    			int xx = dir[i][0] +ad.first;
    			int yy = dir[i][1] +ad.second;
    			if(cp(xx, yy))
    			{
    				dis[xx][yy] = dis[ad.first][ad.second] + 1;
    				q.push(make_pair(xx, yy));
    			}
    		}
    	}
    }
    
    int main()
    {
    	int ex, ey; 
    	ios::sync_with_stdio(false);
    	memset(dis, -1, sizeof(dis));
    	cin >> m >> n;
    	for(int i=1;i<=n;i++)
    	{
    		for(int j=1;j<=m;j++)
    		{
    			cin>>str[i][j];
    			if(str[i][j]=='K')
    			{
    				q.push(make_pair(i,j));
    				dis[i][j]=0;
    			}
    			if(str[i][j]=='H')
    			{
    				ex=i;
    				ey=j;
    			}
    		}
    	}
    	cout<<bfs(ex,ey);
    	return 0;
    }
    

    信息

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