剑指offer12:矩阵中的路径

#include<iostream>
using namespace std;
class Solution {
public:
	bool hasPath(char* matrix, int rows, int cols, char* str)
	{
		int pathLength = 0;
		bool *isVisited = new bool[rows*cols];
		memset(isVisited, 0, rows*cols);
		for (int row = 0; row < rows; row++)
			for (int col = 0; col < cols; col++)
			{
				if (hasPathCore(matrix, rows, cols, row, col, pathLength, str, isVisited))
				{
					delete[]isVisited;
					return true;
				}

			}
		delete[]isVisited;
		return false;

	}

	bool hasPathCore(char* matrix, int rows, int cols, int row, int col, int &pathLength, const char*str, bool* isVisited)
	{
		bool hasPath = false;
		if (str[pathLength] == '\0')
			return true;
		if (row >= 0 && row<rows && col >= 0 && col<cols && matrix[row*cols + col] == str[pathLength] && !isVisited[row*cols + col])
		{
			isVisited[row*cols + col] = true;//错误,原本写的是==,这一点一定要注意到,遇到过好几次这个错误了
			pathLength++;
			hasPath = hasPathCore(matrix, rows, cols, row + 1, col, pathLength, str, isVisited) ||
				hasPathCore(matrix, rows, cols, row - 1, col, pathLength, str, isVisited) ||
				hasPathCore(matrix, rows, cols, row, col + 1, pathLength, str, isVisited) ||
				hasPathCore(matrix, rows, cols, row, col - 1, pathLength, str, isVisited);
			if (!hasPath)
			{
				--pathLength;
				isVisited[row*cols + col] = false;//关于此处为什么要设为false,如果只是单次从某一点开始搜索的话,不需要改,
												//但是这里hasPath函数是以栅格中每个点作为起点都尝试一遍,而isVisited表只有一个,所以需要进行变为false
												//如果在hasPath里每次循环都memset(Visited)的话,这里就不用改为false了
			}
		}

		for (auto i = 0; i < rows; i++)
		{
			for (auto j = 0; j < cols; j++)
			{
				cout << isVisited[i * cols + j] << " ";
			}
			cout << endl;
		}
		cout << endl;

		return hasPath;
	}
};


int main()
{
	//char a[12] = { 'A','B','C','E','S','F','C','S','A','D','E','E' };
	char *a = "ABCEHJIG\
SFCSLOPQ\
ADEEMNOE\
ADIDEJFM\
VCEIFGGS";
	Solution S;
	std::cout<<S.hasPath(a, 5, 8, "SGGFIECVAASABCEHJIGQEM");
}

猜你喜欢

转载自blog.csdn.net/u012686154/article/details/81774376