c++迷宫可视化DFS编程项目代码

#include <bits/stdc++.h>
using namespace std;

struct point {
	int x;
	int y;
	int step;
};

int n, m, sx, sy, ex, ey;
int flag = 1000000;
char temp;
bool tag = false;
bool is_find = false;
int arr[103][103], v[103][103];

void show_v(void) {
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			if (v[i][j] != -1) {
				cout << " " << v[i][j];
			} else {
				cout << v[i][j];
			}
			cout << " ";

		}
		cout << "       ";
		for (int j = 1; j <= m; j++) {
			cout << arr[i][j] << " ";
		}
		cout << endl;
	}
	cout << endl;
}

bool bfs(int nx, int ny, int step) {
	if (is_find) {
		//return true;
	}
	if (arr[nx][ny] != 1) {
		return false;
	}
	if (v[nx][ny] != -1 && step >= v[nx][ny]) {
		return false;
	}
	v[nx][ny] = step;
	show_v();
	cin >> temp;
	if (nx ==  ex && ny == ey && flag >= step) {
		//cout << step << endl;
		tag = true;
		is_find = true;
		if (flag >= step) {
			flag = step;
		}
		//return true;
	}

	return (
	           bfs(nx + 1, ny, step + 1)
	           || bfs(nx, ny + 1, step + 1)
	           || bfs(nx - 1, ny, step + 1)
	           || bfs(nx, ny - 1, step + 1)
	       );

}

void __Input(void) {
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			cin >> arr[i][j];
	cin >> sx >> sy >> ex >> ey;
	for (int i = 0; i <= n + 1; i++)
		for (int j = 0; j <= m + 1; j++)
			v[i][j] = -1;




}//init
void _Input(void) {
	cin >> n;
	m = n;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++) {
			char number = 'a';
			cin >> number;
			if (number == '0') {
				arr[i][j] = 1;
			} else {
				arr[i][j] = 0;
			}
		}
	cin >> sx >> sy >> ex >> ey;
	for (int i = 0; i <= n + 1; i++)
		for (int j = 0; j <= m + 1; j++)
			v[i][j] = -1;
}//init

int main() {
	__Input();
	bfs(sx, sy, 0);
	if (tag) {
		cout << flag;
	} else {
		cout << "No answer!";
	}
	return 0;
}
// welldown!

/*
6 6
1 0 1 1 1 1
1 1 1 0 1 0
1 0 1 0 1 1
1 0 1 0 0 1
1 1 0 1 1 1
0 1 0 1 0 1
1 1
6 6
*/

/*
6 8
1 0 1 1 1 1 1 1
1 1 1 0 1 0 0 1
1 0 1 0 1 1 1 1
1 0 1 0 1 1 1 0
1 0 1 1 1 0 1 1
1 1 1 0 1 1 1 1
1 1
6 8
*/

以上代码为初算,运行结果截图

其中01迷宫的dfs搜索c++代码,1表示通路0表示墙。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值