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

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

相关推荐
玖玥拾26 分钟前
C/C++ 基础笔记(十四)多态与模板编程
c语言·c++·多态·模板
想吃火锅10051 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
Roann_seo%1 小时前
C++文件操作完全指南:从文本读写到二进制文件处理
开发语言·c++
坚果派·白晓明2 小时前
【鸿蒙PC】SDL3 适配:AtomCode + Skills 快速集成 NAPI 测试工具
c++·华为·ai编程·harmonyos·atomcode
云絮.2 小时前
数据库操作
数据库·mysql·算法·oracle
小林ixn2 小时前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
凡人叶枫2 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
凡人叶枫4 小时前
Effective C++ 条款16:成对使用 new 和 delete 时要采取相同形式
开发语言·c++·effective c++
菜鸟‍4 小时前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
不吃土豆的马铃薯4 小时前
C++ 高性能网络缓冲区 Buffer 源码解析
linux·服务器·开发语言·网络·c++