数据结构与算法学习笔记(三)——递归算法

一.卒过河问题

        

        卒A只能向下走一格或者向右走一格,想要到达B点,但是路线中间有一匹马,马的攻击的点是不能经过的(图中有八个,P1-P8,马的那一个点可以通过),求解卒A的过河路线。

        本题采用递归算法,识别卒A的下一步是否可行,可行返回True,得到最终的路径。

        

#include<iostream>
#include<vector>
using namespace std;
int map[5][9] = { {0,0,0,1,0,1,0,0,0},{0,0,1,0,0,0,1,0,0},{0,0,0,0,0,0,0,0,0},{0,0,1,0,0,0,1,0,0},{0,0,0,1,0,1,0,0,0} };

void zuguohe(int x,int y,int& count,vector<int> line) {
	if (map[y][x] == 1) return;
	line.push_back(x);
	line.push_back(y);
	if (x == 8 && y == 4) {
		count++;
		for (int i = 0; i < line.size() - 3; i+=2) {
			cout << '(' << line[i] << ',' << line[i + 1] << ')' << "->";
		}
		cout << '(' << line[line.size() - 2] << ',' << line[line.size() - 1] << ')' << endl;
		return;
	}
	if (x == 8 && y < 4) {
		zuguohe(x, y+1, count, line);
	}
	else if (y == 4 && x < 8) {
		zuguohe(x+1, y, count, line);
	}
	else {
		zuguohe(x, y+1, count, line);
		zuguohe(x+1, y, count, line);
	}
	
}
int main() {
	int count = 0;
	vector<int> line;
	zuguohe(0,0,count,line);
	cout << count;
	return 0;
}

求解的结果

二.走迷宫问题以及可视化

        根据卒过河问题,拓展成随机生成一个迷宫,然后随机生出入口和出口,使用递归算法进行路径的求解(此处采用python代码)。

        

import numpy as np
import matplotlib.pyplot as plt
'''生成随机地图'''
n=int(input("迷宫的大小:"))
map=np.random.randint(0,2,size=[n,n])
#随机出入口
entrance=np.random.randint(0,n,size=2)
exit=np.random.randint(0,n,size=2)
map[entrance[0]][entrance[-1]]=0
map[exit[0]][exit[-1]]=0
deriction=[(0,1),(1,0),(0,-1),(-1,0)]
print(entrance)
print(exit)

print(map)
'''绘制图像'''
def draw(line):
    x=[]
    y=[]
    for i in range(n):
        for j in range(n):
            if(map[i][j]==1):
                y.append(i)
                x.append(j)
    plt.scatter(x,y,color='black',s=20)
    x1=[]
    y1=[]
    for i in range(len(line)):
        y1.append(line[i][0])
        x1.append(line[i][-1])
    plt.scatter(x1,y1,color='green',s=20)
    plt.scatter(entrance[-1],entrance[0],color='red',s=20)
    plt.scatter(exit[-1],exit[0],color='red',s=20)
    plt.show()

'''走迷宫'''
def mark(mapl,pos):
    mapl[pos[0]][pos[1]]=2
def passible(mapl,pos):
    if(pos[0]<0 or pos[0]>=n or pos[1]<0 or pos[1]>=n):
        return False
    return mapl[pos[0]][pos[1]]==0
def find_path(mapl,pos,exit):
    mark(mapl,pos)
    if(pos[0]==exit[0] and pos[1]==exit[1]):
        path.append(pos)
        return True
    for i in range(len(deriction)):
        next_pos=(pos[0]+deriction[i][0],pos[1]+deriction[i][1])
        if passible(mapl,next_pos):
            if find_path(mapl,next_pos,exit):
                print((str(pos[0]),str(pos[1])),'->')
                path.append(pos)
                return True
    return False




path=[]
flag=find_path(map,entrance,exit)
draw(path)
if(not flag):
    print('404 not found!')

        

随机生成的地图大部分都是无解的。

 

其中有解的情况(只保存了一个解):

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值