• 简简单单的寻路算法


    今天搞了寻路算法   搞了好久  唉  瞬间感觉智商捉急啊  = =

    直接上代码咯

    主函数:

                //  随机生成一个10*10的迷宫(可以用*表示起点,#表示终点,0代表不可以通过,1代表可以通过),假如[0,0] 为入口 [9,9] 为出口。
                //   (1)在控制台上显示该迷宫
                //   (2)利用栈结构求解该迷宫是否能抵达出口(入口与出口是否联通)。
                //   (3)如能抵达出口,输出从入口到出口的行走路径。
    
                Maze maze = new Maze();
                maze.Show();
                maze.Find();
                maze.Show();                        


    maze类:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace cs12
    {
            public struct Position
        {
            public int x;
            public int y;
            public Position(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }
    class Maze { Position pos = new Position(0, 0); int[,] map = new int[10, 10]; public Stack<Position> route = new Stack<Position>(); public Maze () { Random rd = new Random(); for (int i = 0; i < this.map.GetLength(0); i++) { for (int j = 0; j < this.map.GetLength(1); j++) { this.map[i, j] = rd.Next(4); if (this.map[i, j] > 0) { this.map[i, j] = 1; } } } map[0, 0] = 1; map[9, 9] = 1; route.Push(new Position(0, 0)); route.Push(new Position(0, 0)); } public void Show() { for (int i = 0; i < map.GetLength(0); i++) { for (int j = 0; j < map.GetLength(1); j++) { if (i == 0 && j == 0) { Console.Write("* "); } if (map[i, j] == 0) { Console.Write(""); } else if (map[i, j] == 7 ) { Console.Write(""); } else { Console.Write(" "); } } Console.WriteLine(); } } public int Find() { //走,,上下左右 if (pos.x < 9 && map[pos.x+1, pos.y] == 1) { pos.x += 1; route.Push(new Position(pos.x, pos.y)); //储存路径 map[pos.x, pos.y] = 7; } else if (pos.y < 9 && map[pos.x, pos.y+1] == 1) { pos.y += 1; route.Push(new Position(pos.x, pos.y)); map[pos.x, pos.y] = 7; } else if (pos.x > 0 && map[pos.x - 1, pos.y] == 1) { pos.x -= 1; route.Push(new Position(pos.x, pos.y)); map[pos.x, pos.y] = 7; } else if (pos.y > 0 && map[pos.x, pos.y-1] == 1) { pos.y -= 1; route.Push(new Position(pos.x, pos.y)); map[pos.x, pos.y] = 7; } else { route.Pop(); pos = route.Peek(); } Position prepos = route.Peek(); if (prepos.x == 9 && prepos.y == 9) { Console.WriteLine("可以到达出口"); return 0; } else if (route.Count == 1) { return 0; } else { return this.Find(); } } } }


    运行结果:

  • 相关阅读:
    什么是函数式编程
    红包算法
    laravel中查看执行的SQL语句
    身份证号信息后台匹配
    在函数内部访问外部的变量
    设计模式-观察者模式
    laravel查询构造器操作数据库
    linux根目录文件夹的作用
    关于laravel连接数据库报错
    设定起始日期,遍历到今天的日期
  • 原文地址:https://www.cnblogs.com/little-sun/p/4354404.html
Copyright © 2020-2023  润新知