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

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

相关推荐
pq21712 分钟前
java实现遗传算法
算法
木井巳43 分钟前
【递归算法】单词搜索
java·算法·leetcode·决策树·深度优先
咚咚王者1 小时前
人工智能之RAG工程 第一章 RAG 基础与前置知识
人工智能·算法
handler011 小时前
【算法模板】最小生成树:稠密图选 Prim,稀疏图选 Kruskal
c语言·数据结构·c++·算法
许长安2 小时前
RPC 异步调用基本使用方法:基于官方helloworld-async 示例
c++·经验分享·笔记·rpc
Chase_______2 小时前
LeetCode 2461 & 1423:定长滑窗变体精讲,从 HashMap 判重到正难则反的转化技巧
算法·leetcode·职场和发展
sparEE2 小时前
c++面向对象:对象的赋值
开发语言·c++
此生决int2 小时前
快速复习之数据结构篇——栈和队列
数据结构·c++
WL_Aurora2 小时前
【每日一题】二分算法
python·算法
昵称小白2 小时前
子串专题部分
数据结构·算法·哈希算法