dfs TLE了 求大佬优化
查看原帖
dfs TLE了 求大佬优化
757864
ruye楼主2023/8/6 14:34
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define int long long
#define double double long
#define endl '\n'
typedef pair<int, int> pii;
inline int read(){
    char c = getchar();int x = 0, f = 1;
    while(c < '0' || c > '9'){if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9'){x = x * 10 + c - '0';c = getchar();}
    return x * f;
}

const int N = 510;
int h, w;
char c[N][N];
bool vis[N][N];
bool is_ok = 0;
int dx[] = {0, 1, 0, -1, 0};
int dy[] = {0, 0, 1, 0, -1};
string s = "snuke";

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


void dfs(int x, int y, int cnt){
    if(x == h && y == w){
        is_ok = 1;
        return ;
    } 
    if(is_ok) return ;

    for(int i = 1; i <= 4; i ++ ){
        int nx = x + dx[i], ny = y + dy[i];
        if(!vis[nx][ny] && check(nx, ny) && c[nx][ny] == s[(cnt + 1) % 5]){
            vis[nx][ny] = 1;
            dfs(nx, ny, cnt + 1);
            vis[nx][ny] = 0;
        }
    }

}


signed main(){
    IOS;
    cin >> h >> w;
    for(int i = 1; i <= h; i ++ )
        for(int j = 1; j <= w; j ++ ) cin >> c[i][j];

    if(c[1][1] == 's') dfs(1, 1, 0);
 	
    if(is_ok) cout << "Yes" << endl;
    else  cout << "No" << endl;
    return 0;
}

代码如上 %

2023/8/6 14:34
加载中...