Lemon_zqp @ 2024-01-14 12:09:22
#include<bits/stdc++.h>
using namespace std;
bool mp[105][105];
int n, m;
int dx[5] = {-1, 1, 0, 0};
int dy[5] = {0, 0, -1, 1};
bool dfs(int x, int y){
if(x == n && y == m){
return true;
}
for(int i = 0; i < 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && mp[nx][ny]){
mp[nx][ny] = false;
cout << nx << " " << ny << endl;
dfs(nx, ny);
mp[nx][ny] = true;
}
}
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
char a;
cin >> a;
if(a == '.'){
mp[i][j] = true;
}
else{
mp[i][j] = false;
}
}
}
if(dfs(1, 1)){
cout << "Yes";
}
else{
cout << "No";
}
return 0;
}
by _int123_ @ 2024-01-14 12:43:41
@Lemon_zqp dfs里没有return false
的操作,而且你代码显然tle
by _int123_ @ 2024-01-14 12:52:30
@Lemon_zqp 你可以试试bfs
AC 代码:
#include<bits/stdc++.h>
#define int long long
using namespace std;
int a[100][105],v[105][105];
int n,m;
struct node
{
int x,y;
};
queue <node> q;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
bool bfs(int x,int y)
{
v[x][y]=1;
q.push({x,y});
while(!q.empty())
{
node w=q.front();
q.pop();
if(w.x==n&&w.y==m) return true;
for(int i=0;i<4;i++)
{
int xx=w.x+dx[i];
int yy=w.y+dy[i];
if(xx>0&&yy>0&&xx<=n&&yy<=m&&v[xx][yy]==0&&a[xx][yy]==1)
{
q.push({xx,yy});
v[xx][yy]=1;
}
}
}
return false;
}
signed main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
char c;
cin>>c;
if(c=='.') a[i][j]=1;
}
if(bfs(1,1)==true) cout<<"Yes";
else cout<<"No";
return 0;
}
by Lemon_zqp @ 2024-01-15 13:00:06
@int123
我按照你的代码改了一下bfs,但……好像样例没过……
#include<bits/stdc++.h>
using namespace std;
bool mp[105][105];
int n, m;
int dx[5] = {-1, 1, 0, 0};
int dy[5] = {0, 0, -1, 1};
struct node{
int x, y;
};
queue<node> q;
void bfs(int x, int y){
mp[x][y] = false;
q.push({x, y});
while(!q.empty()){
node w = q.front();
q.pop();
if(w.x == n && w.y == m){
cout << "Yes";
exit(0);
}
for(int i = 0; i < 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && mp[nx][ny]){
q.push({nx, ny});
mp[nx][ny] = false;
}
}
}
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
char a;
cin >> a;
if(a == '.'){
mp[i][j] = true;
}
else{
mp[i][j] = false;
}
}
}
bfs(1, 1);
cout << "No";
return 0;
}