老鼠迷宫问题递归解法

迷宫如下:
在这里插入图片描述
不是最优解,仅供参考!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*
 * 
 * 老鼠迷宫问题:有一个迷宫,在迷宫的某个出口放着一块奶酪。将一只老鼠由某个入口处放进去,它必须穿过迷宫,找到奶酪。请找出它的行走路径。
 * 9*9自定义迷宫
 * 
 */

namespace MouseMazeTest
{
    class Program
    {

        public static int[,] maze = new int[9, 9] {
            {0, 0, 0, 1, 0, 0, 0, 1, 1 },
            {0, 1, 1, 1, 0, 0, 0, 1, 1 },
            {0, 1, 0, 0, 0, 0, 0, 0, 0 },
            {1, 1, 1, 1, 1, 1, 1, 0, 0 },
            {0, 1, 0, 0, 0, 0, 1, 0, 0 },
            {0, 1, 0, 0, 1, 1, 1, 0, 0 },
            {0, 1, 0, 0, 1, 0, 0, 1, 0 },
            {0, 1, 0, 1, 1, 1, 1, 1, 1 },
            {0, 1, 0, 0, 0, 0, 0, 0, 0 }
        };

        static void Main(string[] args)
        {
            FindWay(maze, 0, 3, 7, 8);
        }

        public static void FindWay(int[,] maze, int sx, int sy, int ex, int ey)
        {
            List<string> way = new List<string>();

            if (FindWay(way, maze, sx, sy, ex, ey))
            {
                Console.WriteLine("找到路了!");
                foreach (string str in way)
                    Console.Write(str + "-");
                Console.WriteLine("");
            }
            else
            {
                foreach (string str in way)
                    Console.Write(str + "-");
                Console.WriteLine("没找到啊!");
            }

            Console.ReadLine();
        }

        public static bool FindWay(List<string> way, int[,] maze, int sx, int sy, int ex, int ey)
        {
            way.Add(sx+","+sy);

            if (sx == ex && sy == ey)
                return true;
            else if (sx - 1 > -1 && maze[sx - 1, sy] == 1 && !way.Contains((sx - 1) +"," + sy) && FindWay(way, maze, sx - 1, sy, ex, ey))
                return true;
            else if (sy - 1 > -1 && maze[sx, sy - 1] == 1 && !way.Contains(sx +"," + (sy - 1)) && FindWay(way, maze, sx, sy - 1, ex, ey))
                return true;
            else if (sx + 1 < 9 && maze[sx + 1, sy] == 1 && !way.Contains((sx + 1) +"," + sy) && FindWay(way, maze, sx + 1, sy, ex, ey))
                return true;
            else if (sy + 1 < 9 && maze[sx, sy + 1] == 1 && !way.Contains(sx +"," + (sy + 1)) && FindWay(way, maze, sx, sy + 1, ex, ey))
                return true;
            else
                way.Remove(sx + "," + sy);
            return false;
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值