When BFS is searching for a water question ~~~~
#include<iostream>#include<string.h>#include<cstdio>#include<string>#include<queue>using namespace std;int map[9][9]={1,1,1,1,1,1,1,1,1, 1,0,0,1,0,0,1,0,1, 1,0,0,1,1,0,0,0,1, 1,0,1,0,1,1,0,1,1, 1,0,0,0,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,0,0,0,1, 1,1,1,1,1,1,1,1,1};int dx[]={0,0,1,-1};int dy[]={1,-1,0,0};struct point{int x;int y;int step;}po;bool visit[10][10];int sx,sy,ex,ey;int step;int bfs(int x,int y){memset(visit,false,sizeof(visit));queue<point>q;po.x=x;po.y=y;po.step=0;q.push(po);visit[x][y]=true;while(!q.empty()){po=q.front();q.pop();x=po.x;y=po.y;step=po.step;if(x==ex&&y==ey) return step;for(int i=0;i<4;++i){int x1=x+dx[i];int y1=y+dy[i];if(!map[x1][y1]&&!visit[x1][y1]&&x1>=0&&x1<=8&&y1>=0&&y1<=8){ po.x=x1;po.y=y1;po.step=step+1;q.push(po); visit[x1][y1]=true;}}}}int main(){int T;cin>>T;while(T--){cin>>sx>>sy>>ex>>ey;cout<<bfs(sx,sy)<<endl;}return 0;}
DFS
# Include <iostream> # include <string. h> # include <cstdio> # include <string> # include <queue> using namespace STD; int map [9] [9] =, 1, 1, 1, 1, 1, 1, 1, 1}; int DX [] = {0, 1,-1}; int dy [] = {1,-1, 0}; struct point {int X; int y; int step;} po; int Sx, Sy, ex, ey; int step, minstep; V Oid DFS (int x, int y) {If (x = ex & Y = ey) {minstep = min (step, minstep); return ;} // end condition for (INT I = 0; I <4; ++ I) {int X1 = DX [I] + X; int Y1 = Dy [I] + Y; if (x1> = 0 & X1 <= 8 & Y1> = 0 & Y1 <= 8 &&! Map [X1] [Y1]) {step ++; Map [X1] [Y1] = 1; DFS (x1, Y1); map [X1] [Y1] = 0; // trace .... Step -- ;}} int main () {int t; scanf ("% d", & T); While (t --) {step = 0; minstep = 0 xffffff; scanf ("% d", & Sx, & Sy, & Ex, & ey); map [SX] [sy] = 1; DFS (sx, sy); map [SX] [sy] = 0; printf ("% d \ n", minstep);} return 0 ;}