矩阵中的路径

44 篇文章 0 订阅
43 篇文章 0 订阅

//请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
//路径可以从矩阵中任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条
//路径经过了矩阵的某一格,那么该路径不能再次进入该格子。

#include "iostream"
#include "vector"

using namespace std;

//回溯法
void construct_candidates(vector<pair<int, int> >& c, pair<int, int>& current, 
								char next, char** mat, vector<vector<bool> >& accessible)
{
	int rows = accessible.size();
	int cols = accessible[0].size();

	int x = current.first;
	int y = current.second; 

	if (x-1 >= 0 && mat[x-1][y] == next && accessible[x-1][y]) c.push_back(make_pair(x - 1, y));
	if (y - 1 >= 0 && mat[x][y - 1] == next && accessible[x][y - 1]) c.push_back(make_pair(x, y - 1));
	if (x + 1 < rows && mat[x + 1][y] == next && accessible[x + 1][y]) c.push_back(make_pair(x + 1, y));
	if (y + 1 < cols && mat[x][y + 1] == next && accessible[x][y + 1]) c.push_back(make_pair(x, y + 1));
	
}
void backTracking(vector<pair<int, int> >& path, vector<vector<bool> >& accessible, 
					char** mat,	char* str, bool* found)
{
	if (path.size() == strlen(str))
		*found = true;
	else
	{
		vector<pair<int, int> >c;
		construct_candidates(c, path.back(), str[path.size()], mat, accessible);
		for (size_t i = 0; i < c.size(); ++i)
		{
			int nx = c[i].first;
			int ny = c[i].second;
			path.push_back(c[i]);
			accessible[nx][ny] = false;
			backTracking(path, accessible, mat, str, found);
			if (*found)
				break;
			path.pop_back();
			accessible[nx][ny] = true;
		}
	}
}

bool hasPath(char** mat, int rows, int cols, char* str)
{
	if (mat == NULL || str == NULL || rows <= 0 || cols <= 0)
		return false;

	vector<pair<int, int> > path;

	vector<vector<bool> >accessible(rows, vector<bool>(cols, true));
	bool found = false;
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cols; j++)
		{
			if (mat[i][j] == str[0])
			{
				path.push_back(make_pair(i, j));
				backTracking(path, accessible, mat, str, &found);
			}
				
			if (found)
				return found;
		}
	}
	return found;
}


void test()
{
	char *mat[] = { "abce", "sfcs", "adee" };
	char str[] = "bcced";

	cout << boolalpha << hasPath(mat, 3, 4, str) << endl;
}

int main()
{
	test();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值