大佬大佬,我错哪了~(^_^)~

P1746 离开中山路

@[cairuihe88](/user/635737) 两个dx? ``` const int dx[4]={0,0,-1,1}; const int dx[4]={-1,1,0,0}; ```
by coldy_rainy @ 2022-02-07 15:24:25


@[cairuihe88](/user/635737) ```cpp #include<bits/stdc++.h> #define int long long using namespace std; int n,sx,sy,fx,fy; char a[1005][1005]; bool vis[1005][1005]; int dx[4]={0,0,-1,1}; int dy[4]={-1,1,0,0}; struct node { int x,y,step; }; int bfs(int x,int y) { queue<node> q; node cur={x,y,0}; q.push(cur); vis[x][y]=true; while(q.empty()==false) { node cur=q.front(); q.pop(); if (cur.x==fx&&cur.y==fy) return cur.step; for(int i=0; i<4; i++) { int nx=cur.x+dx[i]; int ny=cur.y+dy[i]; if (nx>0&&nx<=n&&ny>0&&ny<=n&&vis[nx][ny]==false&&a[nx][ny]=='0') { vis[nx][ny]=true; node next={nx,ny,cur.step+1}; q.push(next); } } } return -1; } signed main() { cin >> n; for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) cin >> a[i][j]; cin >> sx >> sy >> fx >> fy; cout << bfs(sx,sy); return 0; } ```
by kdy20100729 @ 2022-02-07 15:25:33


@[cairuihe88](/user/635737) AC代码: ``` #include<bits/stdc++.h> using namespace std; const int N=1005; const int dx[4]={0,0,-1,1}; const int dy[4]={-1,1,0,0}; struct node{ int x,y,dist; }; int n,x1,yy,x2,y2; bool h[N][N],flag[N][N]; queue<node>q; void bfs(){ flag[x1][yy]=true; node tmp; tmp.x=x1; tmp.y=yy; tmp.dist=0; q.push(tmp); while(!q.empty()){ tmp=q.front(); q.pop(); for(int i=0;i<=3;i++){ int tx=tmp.x+dx[i]; int ty=tmp.y+dy[i]; if(tx>=1&&tx<=n&&ty>=1&&ty<=n&&h[tx][ty]&&!flag[tx][ty]){ flag[tx][ty]=true; node tn; tn.x=tx; tn.y=ty; tn.dist=tmp.dist+1; q.push(tn); if(tx==x2&&ty==y2){ cout<<tn.dist; return; } } } } } int main(){ char ch; cin>>n; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++){ cin>>ch; if(ch=='0')h[i][j]=true; } cin>>x1>>yy>>x2>>y2; bfs(); return 0; } ```
by coldy_rainy @ 2022-02-07 15:31:59


@[cairuihe88](/user/635737) 错误点: 【1】 这里: ``` const int dx[4]={0,0,-1,1}; const int dx[4]={-1,1,0,0}; ``` 有两个dx,改成: ``` const int dx[4]={0,0,-1,1}; const int dy[4]={-1,1,0,0}; ``` 即可 【2】 在```bfs```函数里,你没初始压入出发点,加上: ``` q.push(tmp); ``` 即可
by coldy_rainy @ 2022-02-07 15:35:07


@penhaochen@kdy20100729 谢谢各位的帮助,祝各位财源滚滚,心想事成
by TaoTi @ 2022-02-08 08:23:12


|