2 条题解

  • 4
    @ 2026-8-21 10:31:11
    #include<bits/stdc++.h>
    using namespace std;
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    int n, m;
    vector<string> grid;
    void dfs(int x, int y) {
        grid[x][y] = '0';
        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 && grid[nx][ny] != '0') {
                dfs(nx, ny);
            }
        }
    }
    int main() {
        ios_base::sync_with_stdio(false);
        cin.tie(nullptr);
        cin >> n >> m;
        grid.resize(n);
        for (int i = 0; i < n; ++i) cin >> grid[i];
        int cellCount = 0;
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < m; ++j)
                if (grid[i][j] != '0') {
                    cellCount++;
                    dfs(i, j);
                }
        cout << cellCount << endl;
        return 0;
    }
    
    • 2
      @ 2026-8-21 11:07:42
      #include<bits/stdc++.h>
      using namespace std;
      int n,m,ans;
      string s;
      int c[100][100];
      int dx[10]={-1,0,1,0};
      int dy[10]={0,1,0,-1};
      bool check(int x,int y){
          return c[x][y]>=1&&c[x][y]<=9&&x>=1&&x<=n&&y>=1&&y<=m;
      }
      void dfs(int x,int y){
          for(int i=0;i<=3;i++){
              if(check(x+dx[i],y+dy[i])){
                  c[x+dx[i]][y+dy[i]]=0;
                  dfs(x+dx[i],y+dy[i]);
              }
          }
      }
      int main(){
          cin>>n>>m;
          for(int i=1;i<=n;i++){
              cin>>s;
              for(int j=1;j<=m;j++)
                  c[i][j]=s[j-1]-'0';
          }
          for(int i=1;i<=n;i++){
              for(int j=1;j<=m;j++){
                  if(c[i][j]>=1&&c[i][j]<=9){
                      ans++;
                      c[i][j]=0;
                      dfs(i,j);
                  }
              }
          }
          cout<<ans;
          return 0;
      }
      
      • 1

      信息

      ID
      474
      时间
      1000ms
      内存
      64MiB
      难度
      5
      标签
      递交数
      71
      已通过
      28
      上传者