Chinaunix首页 | 论坛 | 博客
  • 博客访问: 320241
  • 博文数量: 23
  • 博客积分: 2115
  • 博客等级: 大尉
  • 技术积分: 371
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-15 16:36
文章分类

全部博文(23)

文章存档

2013年(4)

2012年(4)

2011年(3)

2010年(6)

2009年(5)

2008年(1)

我的朋友

分类: 嵌入式

2012-10-19 16:02:18

参考了 http://www.cppblog.com/christanxw/archive/2006/04/07/5126.html


代码比较简单,也没有对选取opens里最小的元素进行速度优化,比如用heap

close状态直接记录在了cells数组里,好像更方便


点击(此处)折叠或打开

  1. List<DataCell> opens = new List<DataCell>(); //开放列表


  2. DataCell start = cells[15];
  3. DataCell end = cells[99];
  4. start.color = Color.Gold;
  5. end.color = Color.Lime;
  6. opens.Add(start);
  7. for (int i = 0; i < 100; i++)//把所有h初始化掉

  8. {
  9. cells[i].h = (int)Math.Sqrt((cells[i].x - end.x) * (cells[i].x - end.x) + (cells[i].y - end.y) * (cells[i].y - end.y));
  10. }

  11. while (opens.Count > 0)
  12. {
  13. int minindex = 0;
  14. for (int i = 1; i < opens.Count; i++)//找出最小f的节点

  15. {
  16.     if (opens[i].f < opens[minindex].f)
  17.     {
  18.     minindex = i;
  19.     }
  20. }
  21. opens[minindex].fin = true;
  22. int cellid = opens[minindex].id;
  23. int hplus = opens[minindex].f;
  24. if (opens[minindex].id == end.id)//到达目标,退出

  25. {
  26.     int pid = cells[cellid].parent;
  27.     while (pid != 0)
  28.     {
  29.     cells[pid].color = Color.Red;
  30.     pid = cells[pid].parent;
  31.     }
  32.     break;
  33. }
  34. opens.Remove(opens[minindex]);
  35. for (int i = -1; i < 2; i++) //对周围的8各节点进行扫描

  36. {
  37.     for (int j = -1; j < 2; j++)
  38.     {
  39.     if (i == 0 && j == 0)
  40.     {
  41.      continue;
  42.     }
  43.     if (cellid + j * 10 < 0 || cellid + j * 10 >= 100)
  44.     {
  45.      continue;
  46.     }
  47.     if ((cellid % 10) == 0 && i == -1)
  48.     {
  49.      continue;
  50.     }
  51.     if ((cellid % 10) == 9 && i == 1)
  52.     {
  53.      continue;
  54.     }
  55.     if (!cells[cellid + j * 10 + i].fin && !cells[cellid + j * 10 + i].disable)
  56.     {
  57.      int sid = cellid + j * 10 + i;
  58.      int tempg = (int)Math.Sqrt((cells[sid].x - cells[cellid].x) * (cells[sid].x - cells[cellid].x) + (cells[sid].y - cells[cellid].y) * (cells[sid].y - cells[cellid].y));
  59.      int tempf = tempg + cells[sid].h + hplus;
  60.      if (cells[sid].f == 0 || cells[sid].f > tempf)
  61.      {
  62.         cells[sid].g = tempg;
  63.         cells[sid].f = tempf;
  64.         cells[sid].parent = cellid;
  65.      }
  66.      if (!opens.Contains(cells[sid]))
  67.      {
  68.         opens.Add(cells[sid]);
  69.      }
  70.     }
  71.     }
  72. }



 

阅读(387) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~