1 solutions

  • 1
    @ 2026-1-28 15:26:45

    这一题是一道经典的BFS,由于这一题的坐标是反着的(1, 1)是左下角。所以搜索的坐标给改变一下。下面附上AC代码。

    #include <bits/stdc++.h>
    using namespace std;
    const int N = 205;
    char a[N][N];
    int vis[N][N];
    int n, m, sx, sy, res;
    
    int dx[] = {0, 0, 1, -1, 1, -1, 1, -1};
    
    int dy[] = {1, -1, 0, 0, 1, 1, -1, -1};
    
    struct node {
    	int x, y, t;
    };
    
    queue<node> q;
    void bfs() {
    	q.push({sx, sy, 0});
    	while (!q.empty()) {
    		node t = q.front();
    		q.pop();
    		res = t.t;
    		for (int i = 0; i < 8; i++) {
    			int nx = t.x + dx[i];
    			int ny = t.y + dy[i];
    			if (nx < 1 || nx > n || ny < 1 || ny > m)
    				continue;
    			if (vis[nx][ny])
    				continue;
    			if (a[nx][ny] == '*')
    				continue;
    			vis[nx][ny] = 1;
    			q.push({nx, ny, t.t + 1});
    		}
    	}
    }
    
    int main() {
    	ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
    	cin >> m >> n >> sy >> sx;
    	sx = n - sx + 1;
    	for (int i = 1; i <= n; i++) {
    		for (int j = 1; j <= m; j++) {
    			cin >> a[i][j];
    		}
    	}
    	vis[sx][sy] = 1;
    	bfs();
    	cout << res << endl;
    	return 0;
    }
    /*
    4 3 2 1
    ....
    ..*.
    .**.
    
    
    */
    

    Information

    ID
    7138
    Time
    1000ms
    Memory
    125MiB
    Difficulty
    5
    Tags
    # Submissions
    32
    Accepted
    5
    Uploaded By