[关闭]
@xunuo 2017-01-18T13:11:23.000000Z 字数 1205 阅读 908

忘了标题-----简单的bfs

BFS


bfs代码:

  1. int BFS()
  2. {
  3. node now,next;
  4. queue<node>q;//队列
  5. now.x=x;
  6. now.y=y;
  7. now.step=0;
  8. q.push(now);//初始点入队
  9. while(!q.empty())
  10. {
  11. now=q.front();
  12. q.pop();
  13. if(a[now.x][now.y]=='C')
  14. {
  15. count=now.step;
  16. return count;
  17. }
  18. for(i=0;i<4;i++)//p的所有邻接点
  19. {
  20. next=now;
  21. next.x+=dir[i][0];
  22. next.y+=dir[i][1];
  23. if(next.x>=0&&next.x<r&&next.y>=0&&next.y<c&&a[next.x][next.y]!='*'&&vis[next.x][next.y]==0)
  24. {
  25. vis[next.x][next.y]=1;
  26. next.step=now.step+1;
  27. q.push(next);
  28. }
  29. }
  30. }
  31. return -1;
  32. }

完整代码:

  1. #include<stdio.h>
  2. #include<queue>
  3. using namespace std;
  4. int dir[4][2]={1,0,-1,0,0,1,0,-1};//方向数组
  5. int vis[111][111];//标记数组
  6. char a[111][111];//存路径的数组
  7. int r,c,x,y,count,i;
  8. struct node
  9. {
  10. int x;
  11. int y;
  12. int step;
  13. };
  14. int BFS()
  15. {
  16. node now,next;
  17. queue<node>q;//队列
  18. now.x=x;
  19. now.y=y;
  20. now.step=0;
  21. q.push(now);//初始点入队
  22. while(!q.empty())
  23. {
  24. now=q.front();
  25. q.pop();
  26. if(a[now.x][now.y]=='C')
  27. {
  28. count=now.step;
  29. return count;
  30. }
  31. for(i=0;i<4;i++)//p的所有邻接点
  32. {
  33. next=now;
  34. next.x+=dir[i][0];
  35. next.y+=dir[i][1];
  36. if(next.x>=0&&next.x<r&&next.y>=0&&next.y<c&&a[next.x][next.y]!='*'&&vis[next.x][next.y]==0)
  37. {
  38. vis[next.x][next.y]=1;
  39. next.step=now.step+1;
  40. q.push(next);
  41. }
  42. }
  43. }
  44. return -1;
  45. }
  46. int main()
  47. {
  48. int i,j,ct;
  49. scanf("%d%d",&r,&c);
  50. for(i=0;i<r;i++)
  51. scanf("%s",&a[i]);
  52. for(i=0;i<r;i++)
  53. for(j=0;j<c;j++)
  54. if(a[i][j]=='B')
  55. {
  56. x=i;
  57. y=j;
  58. }
  59. ct=BFS();
  60. printf("%d\n",ct);
  61. return 0;
  62. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注