3 solutions

  • 0
    @ 2023-5-15 17:55:42

    这道题我使用的是DFS的算法

    #include <bits/stdc++.h>
    
    using namespace std;
    const int N = 100 + 10;
    
    bool vis[N][N] = {false};
    char mp[N][N];
    int dx[4] = {0, 0, -1, 1};//定义x方向的移动
    int dy[4] = {-1, 1, 0, 0};//定义y方向的移动
    int r, c; //草丛的宽和长
    int ans = 0; //记录草丛数量
    int fg = 0; //记录岛屿
    
    void dfs(int x, int y) {
    	if (vis[x][y] == true) {
    		return;
    	}//每次调用都检查一下vis是否被访问
    	vis[x][y] = true;
    	for (int i = 0; i < 4; i++) {
    		int nx = x + dx[i]; //向四个方向扩散
    		int ny = y + dy[i];
    		if (vis[nx][ny] == false && mp[nx][ny] == '#') {
    			dfs(nx, ny);//如果四个方向存在连接的,那么就进行标记
    		}
    	}
    }
    
    int main() {
    	cin >> r >> c;
    	for (int i = 0; i < r; i++) {
    		for (int j = 0; j < c; j++) {
    			cin >> mp[i][j];
    		}
    	}
    	for (int i = 0; i < r; i++) {
    		for (int j = 0; j < c; j++ ) {
    			if (mp[i][j] == '#' && vis[i][j] == false) {
    				dfs(i, j); //遍历每一块土地
    				ans++;
    			}
    		}
    	}
    	cout << ans;
    	return 0;
    }
    

    Information

    ID
    720
    Time
    1000ms
    Memory
    64MiB
    Difficulty
    1
    Tags
    # Submissions
    62
    Accepted
    41
    Uploaded By