迷宫(一)(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,练习了一些入门题目;

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

相关推荐
2301_8002561130 分钟前
数据结构基础期末复习例题
数据结构·算法
劉宇雁40 分钟前
C++ ASCII 3D无尽跑酷游戏
c++·游戏·3d
变量未定义~1 小时前
单调栈-四元组问题
数据结构·算法
冷小鱼1 小时前
AI Agent 核心算法:任务规划(Planning)的深度技术解析
人工智能·算法·planning
杜子不疼.1 小时前
【C++ 在线五子棋对战】- 会话管理模块实现
开发语言·c++
退休倒计时1 小时前
【每日一题】LeetCode 78. 子集 TypeScript
算法·leetcode·typescript
有点。1 小时前
C++深度优先搜索(DFS)的概念(一)
开发语言·c++·深度优先
旖-旎1 小时前
《LeetCode 978 最长湍流子数组 || LeetCode 139 单词拆分》
c++·算法·leetcode·动态规划
aaPIXa6221 小时前
C++大型项目模块化拆分实战记录
开发语言·c++
cxr8281 小时前
第16章 跨域迁移与能力融合——从专家到通才
人工智能·算法·智能体·hermes