Using the breadth-first search algorithm path

Original link: http://www.cnblogs.com/zzandliz/p/5143519.html
Description of the problem: Given a 32x32 map, the map has a number of obstacles, use the blue square to draw, design algorithm to find a path of obstacles can not touch the transfer from the upper left to the lower right corner of the map, and draw the green line .

Ideas: the first to use the full map of the BFS search, find remove obstacles to reach the minimum number of steps per a point outside of the points. And then plotted points around the current path to the minimum number of steps in turn points.

Needless to say you can tell this is a job. . . Code is very rough, with many parts of the variable represented by a specific value, just to show the effect achieved.

 
    
  1. %BFS路径搜索
  2. %Date-2015-12-29
  3. %-----初始化-----
  4. clear all;
  5. clc
  6. z=zeros(32,32);
  7. grd=zeros(32,32);
  8. grd(1,:)=1;
  9. grd(32,:)=1;
  10. grd(:,1)=1;
  11. grd(:,32)=1;
  12. grd(6:12,7:12)=1;
  13. grd(20:27,4:8)=1;
  14. grd(16,22:27)=1;
  15. grd(10:27,18)=1;
  16. grd(7:16,27)=1;
  17. grd(24,12:19)=1;
  18. gimag=grd;
  19. grd1=grd;
  20. Tempx=2;
  21. Tempy=2;
  22. grd(Tempx,Tempy)=2;
  23. grd(31,31)=3131;
  24. distancemin=64;
  25. route=zeros(32,32);%32,32
  26. route(2,2)=1;
  27. length=5;
  28. flag=0;
  29. dirc=0;
  30. xqueue = zeros(3131);
  31. yqueue = zeros(3131);
  32. xqueue(1) = 2;
  33. yqueue(1) = 2;
  34. startflag = 1;
  35. endflag = 1;
  36. while 1
  37. for i=-1:1
  38. for j= -1:1;
  39. if grd(xqueue(startflag)+i,yqueue(startflag)+j)==0||grd(xqueue(startflag)+i,yqueue(startflag)+j)>grd(xqueue(startflag),yqueue(startflag))+1
  40. grd(xqueue(startflag)+i,yqueue(startflag)+j)=grd(xqueue(startflag),yqueue(startflag))+1;
  41. xqueue(endflag+1) = xqueue(startflag)+i;
  42. yqueue(endflag+1) = yqueue(startflag)+j;
  43. endflag = endflag+1;
  44. end
  45. end
  46. end
  47. if grd(31,31) ~= 3131
  48. break;
  49. end
  50. startflag = startflag + 1;
  51. end
  52. xnow = 2;
  53. ynow = 2;
  54. z(2,2) = 1;
  55. for i = 1:100
  56. max = 0;
  57. for p = 1:-1:-1
  58. for q = 1:-1:-1
  59. if grd(xnow+p,ynow+q)>max&&z(xnow+p,ynow+q)==0
  60. max = grd(xnow+p,ynow+q);
  61. xnowmax = xnow+p;
  62. ynowmax = ynow+q;
  63. end
  64. end
  65. end
  66. xnow = xnowmax;
  67. ynow = ynowmax;
  68. route(xnowmax,ynowmax) = 1;
  69. z(xnowmax,ynowmax)=1;
  70. imh = image(cat(3,z,route,gimag));
  71. set(imh, 'cdata', cat(3,z,route,gimag));
  72. drawnow;
  73. pause(0.1);
  74. if xnow==31&&ynow==31
  75. break;
  76. end
  77. end
  78. %
effect:








Reproduced in: https: //www.cnblogs.com/zzandliz/p/5143519.html

Guess you like

Origin blog.csdn.net/weixin_30856965/article/details/94785247