战旗游戏,能走多远的算法(面试题)
朋友参加个面试,面试官问的问题:
就是战旗游戏能走多远的问题,有初始的行动力,不同地形会消耗不同的行动力,然后都能走到那些位置~
刚听到问题的时候,感觉应该是A*的思路来解答,结果是想复杂了,实际比A*还要简单~
做个Demo试试吧~~~~
思路就是从中心点,一圈一圈向外遍历,一直遍历到行动力没了为止。
我这里是用递归做的,核心代码贴在下面。
//初始点
void StartAt(int x, int y, int rest){if (Nodes.Count > y){if (Nodes[y].Count > x){var n = Nodes[y][x];n.SetColor(Color.red);n.rest = rest;}}l.Clear();l.Add(Nodes[y][x]);GoNextStep();}List tmp = new List();
//向外遍历void GoNextStep(){tmp.Clear();foreach (var item in l){int xx = 0;int yy = 0;Debug.Log("-------------------");xx = item.x - 1;yy = item.y;CheckNode(xx, yy, item.rest);xx = item.x + 1;yy = item.y;CheckNode(xx, yy, item.rest);xx = item.x;yy = item.y + 1;CheckNode(xx, yy, item.rest);xx = item.x;yy = item.y - 1;CheckNode(xx, yy, item.rest);}l.Clear();if (tmp.Count > 0){Debug.LogError("tmp.Count " + tmp.Count);l.AddRange(tmp);GoNextStep();}}//检测四周的方块能否继续拓展,同时比较剩余行动力,如果剩余行动力更高,则加入下轮遍历的容器中private void CheckNode(int xx, int yy, int rest){Debug.Log("check x : " + xx + ", y : " + yy);if (Nodes.Count > yy && yy >= 0){if (Nodes[yy].Count > xx && xx >= 0){var n = Nodes[yy][xx];int newRest = rest - n.cost;if (newRest > n.rest){n.rest = newRest;if (n.rest > 0){n.SetColor(Color.green);tmp.Add(n);}else{n.SetColor(Color.red);}}}}}
还是很简单的~
效果如下:


别说~ 做出来还是挺有成就感 挺好玩儿的~ (其实俺特喜欢战棋类游戏~ )
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
项目传上来:https://github.com/PatrickBoomBoom/CheckHowFarCanGo.git
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
