下列代码为本题目的代码,结果为#6, #7 TLE,其余AC 目前没有想到任何其他优化的方法,求优化修改,谢谢!
#include <bits/stdc++.h>
using namespace std;
int n, m;
char board[1501][1501];
int metGrid[1501][1501][2];
const int dx[] = {1,0,-1,0};
const int dy[] = {0,1,0,-1};
const int dircount = 4;
inline int mod(int x, int n){
return (x % n >= 0) ? x % n : (x % n + n);
}
void print(){
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cout << board[i][j];
}
cout << endl;
}
cout << endl;
}
int sx, sy;
bool DFS(int x, int y){
int modx = mod(x,n), mody = mod(y,m);
if(board[modx][mody] == 'X'){
int lrx = metGrid[modx][mody][0];
int lry = metGrid[modx][mody][1];
int lx = x / n, ly = y / m;
return (lx != lrx || ly != lry);
}
else if(board[modx][mody] == '#'){
return false;
}
else{
board[modx][mody] = 'X';
metGrid[modx][mody][0] = x / n;
metGrid[modx][mody][1] = y / m;
for(int dir=0; dir<dircount; dir++){
int newx = x + dx[dir], newy = y + dy[dir];
bool success = DFS(newx, newy);
if(success) return true;
}
board[modx][mody] = '.';
return false;
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
while(cin >> n >> m){
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin >> board[i][j];
if(board[i][j] == 'S'){
sx = i, sy = j;
board[i][j] = '.';
}
}
}
cout << (DFS(sx, sy) ? "Yes" : "No") << endl;
}
return 0;
}