剑指offer 10 矩阵中的路径

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

解法:经典深搜问题,具体思路参照我之前写的这篇https://blog.csdn.net/u010760034/article/details/82801249

class Solution {
public:
	int mov[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };

	bool hasPath(char* matrix, int rows, int cols, char* str)
	{
		bool visited[50][50];//访问标志
		memset(visited, 0, sizeof(visited));
		if (matrix == nullptr || rows < 1 || cols < 1 || str == nullptr)
			return false;
		bool result = false;
		for (int i = 0;i < rows;i++)
		{
			for (int j = 0;j < cols;j++)
			{
				if (matrix[i*cols + j] == str[0])
				{
					//cout << i << j << matrix[i*cols + j] << endl;
					result = DFS(rows,cols,i, j, 1,visited,str,matrix);
					//cout << result << endl;
					if (result)
						break;
					else
						memset(visited, 0, sizeof(visited));
				}
			}
			if (result)
				break;
		}
		if (result)
			return true;
		else
			return false;
	}
	bool DFS(int rows,int cols,int x, int y, int u,bool visited[][50],char* str,char* matrix)
	{
		visited[x][y] = true;
		//cout << u << endl;
		if (u == strlen(str))
			return true;
		for (int j = 0;j < 4;j++)
		{
			int new_x = x + mov[j][0];
			int new_y = y + mov[j][1];
			//cout << new_x << "    " << new_y<<"    "<< u << endl;
			if (new_x >= 0 && new_x < rows && new_y >= 0 && new_y < cols && visited[new_x][new_y] == false && str[u] == matrix[new_x*cols+new_y])
			{
				//cout <<matrix[x*cols + y]<<"    "<<str[u] << endl;
				bool flag = DFS(rows, cols, new_x, new_y, u+1, visited, str, matrix);
				if (flag)
					return true;
			}
		}
		return false;
	}
};

猜你喜欢

转载自blog.csdn.net/u010760034/article/details/83589911