Paste: red and black

Author: paste
Mode: c++
Date: Wed, 27 Oct 2021 12:48:42
Plain Text |
#include <string>
#include <iostream>
#include <cstring>
using namespace std;

const int N = 30;
int w, h, t = 0, ans = 0, ms = 0;
int sx, sy, vis[N][N];
int dx[4] = {0, -1, 0, 1}, dy[4] = {-1, 0, 1, 0}; // 下左上右
string g[N];

int check(int x, int y){
    if(x >= 0 && x < h && y >= 0 && y < w) return 1;
    return 0;
}

int check2(int x, int y){ // 是否有路可走
    for(int i = 0; i < 4; i++){
        int nx = x + dx[i];
        int ny = y + dy[i];
        if(check(nx, ny) && g[nx][ny] == '.' && !vis[nx][ny]) return 1;
    }
    return 0;
}

void dfs(int x, int y, int sum){
    if(!check2(x, y) || sum >= ms){
        ans = max(ans, sum);
        return;
    }
    for(int i = 0; i < 4; i++){
        int nx = x + dx[i];
        int ny = y + dy[i];
        if(check(nx, ny) && g[nx][ny] == '.' && !vis[nx][ny]){
            vis[nx][ny] = 1;
            dfs(nx, ny, sum + 1);
            vis[nx][ny] = 0;
        }
    }
}

int main(){
    
    while(cin >> w >> h && w != 0 && h != 0){
        memset(vis, 0, sizeof vis);
        for(int i = 0; i < h; i ++) cin >> g[i];
        for(int i = 0; i < h; i ++){
            for(int j = 0; j < w; j ++){
                if(g[i][j] == '.') ms ++;
                if(g[i][j] == '@')
                    sx = i, sy = j;
            } 
        }
        vis[sx][sy] = 1;
        dfs(sx, sy, 1);
        cout << ans;
    }
    
    return 0;
}

New Annotation

Summary:
Author:
Mode:
Body: