2 solutions
-
0
bfs不太会,我强行用了dfs
#include<bits/stdc++.h> using namespace std; int n,m,x,y,sx,sy,fx,fy; char ma1[25][25]; int ans[10005];//记录每个到达终点的cnt的值 bool ma2[25][25];//记录是否走过 int opx[5] = {1,0,0,-1}; int opy[5] = {0,1,-1,0}; int cnt,op=0;//cnt 用于计数 ans 用于记录最小的路径 void dfs(int x,int y){ if(x == fx && y == fy){ ans[op] = cnt; op++; } else{ for(int i = 0; i < 4; i++){ int nex = x + opx[i]; int ney = y + opy[i]; if(nex>=1&&nex<=n&&ney>=1&&ney<=m&&(ma1[nex][ney]=='.'||ma1[nex][ney]=='*')&&!ma2[nex][ney]){ ma2[nex][ney] = true; cnt++; dfs( nex, ney); ma2[nex][ney] = false; cnt--; } } } } int main(){ std::ios::sync_with_stdio(false); cin>>n>>m; for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ cin>> ma1[i][j]; if(ma1[i][j]=='@') sx = i,sy = j; if(ma1[i][j]=='*') fx = i, fy = j; } } dfs( sx, sy); int mini=100005; for(int i=0;i<100;i++){ if(ans[i]&&ans[i]<mini) mini=ans[i]; } if(mini != 100005) cout<<mini; else cout<<-1; return 0; }
-
0
吐槽一下关于周日不算本周的事(不要捶我),好的本题是一道bfs的板子题(大概),上代码(献丑了)
#include<iostream> #include<queue> using namespace std; const int N=27; bool v[N][N]; int n,m,flag=0; char a[N][N]; int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1}; struct A{ int step,x,y; }p[N*N]; queue<A>q; int main(){ cin>>n>>m; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cin>>a[i][j]; if(a[i][j]=='@'){ v[i][j]=true; A sta; sta.step=0; sta.x=i; sta.y=j; q.push(sta); } } } while(!q.empty()){ A t=q.front(); v[t.x][t.y]=true; if(a[t.x][t.y]=='*'){ cout<<t.step; flag=1; break; } q.pop(); for(int i=0;i<4;i++){ int xx=t.x+dx[i]; int yy=t.y+dy[i]; if(!v[xx][yy]&&xx>0&&yy>0&&xx<=n&&yy<=m&&a[xx][yy]!='#'){ A next; next.x=xx; next.y=yy; next.step=t.step+1; q.push(next); } } } if(flag==0)cout<<"-1"; return 0; }
- 1
Information
- ID
- 1236
- Time
- 1000ms
- Memory
- 128MiB
- Difficulty
- 6
- Tags
- # Submissions
- 151
- Accepted
- 48
- Uploaded By