迷宫(一)(DFS & BFS)

//新生训练

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
int n, m;
bool f;
char mp[15][15];
int vis[15][15];
int dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
bool in(int x, int y)
{
	return 0 <= x && x < n && 0 <= y && y < m;
}
void dfs(int x, int y)
{
	if (mp[x][y] == 'T')
	{
		f = true;
		return;
	}
	if (!in(x, y) || mp[x][y] == '*' || vis[x][y])
	{
		return;
	}
	vis[x][y] = 1;
	for (int i = 0; i < 4; i++)
	{
		int tx = x + dir[i][0];
		int ty = y + dir[i][1];
		dfs(tx, ty);
	}
	return;
}
int main()
{
	cin >> n >> m ;
	for (int i = 0; i < n; i++)
	{
		cin >> mp[i];
	}
	int x, y;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (mp[i][j] == 'S')
			{
				x = i;
				y = j;
			}
		}
	}
	dfs(x, y);
	if (f)
	{
		cout << "yes" << endl;
	}
	else
	{
		cout << "no" << endl;
	}
	return 0;
}

//笔者新学的DFS和BFS,练习了一些入门题目;

~~~//仅当笔者个人备忘录使用。

相关推荐
shughui1 天前
Python基础面试题:语言定位+数据类型+核心操作+算法实战(含代码实例)
开发语言·python·算法
王老师青少年编程1 天前
信奥赛C++提高组csp-s之拓扑排序详解
c++·算法·拓扑排序·csp·信奥赛·csp-s·提高组
kaikaile19951 天前
matlab计算流场
人工智能·算法·matlab
3GPP仿真实验室1 天前
【Python源码】6G:PyTorch OFDM 教学仿真平台
算法
xie_pin_an1 天前
C++ 从入门到进阶:核心知识与实战指南
java·c++·算法
No0d1es1 天前
2025年12月 GESP CCF编程能力等级认证C++八级真题
开发语言·c++·青少年编程·gesp·ccf
我是个菜鸡.1 天前
多模态算法面经准备
算法
AlenTech1 天前
739. 每日温度 - 力扣(LeetCode)
算法·leetcode·职场和发展
fqbqrr1 天前
2601C++,概念与约束及推导本
c++
xiaowu0801 天前
C#调用 C++ DLL 加载地址方式选择
开发语言·c++·c#