剑指offer-回溯

题目一:

题目描述:

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

class Solution {
public:
	bool solve(const char* matrix, const int& rows, const int& cols, const char* str, int x, int y, bool* record)
	{
		if (*str == '\0') return true;
		if (x >= rows || x<0 || y >= cols || y<0) return false;
		if (record[x*cols + y] == 1 || *str != matrix[x*cols + y]) return false;
		record[x*cols + y] = 1;
		bool res = solve(matrix, rows, cols, str + 1, x + 1, y, record) ||
			solve(matrix, rows, cols, str + 1, x - 1, y, record) ||
			solve(matrix, rows, cols, str + 1, x, y + 1, record) ||
			solve(matrix, rows, cols, str + 1, x, y - 1, record);
		record[x*cols + y] = 0;                       //回溯法的返回处理
		return res;
	}
	bool hasPath(char* matrix, int rows, int cols, char* str)
	{
		bool* record = new bool[rows*cols]();
		for (int i = 0; i<rows*cols; i++)
		{
			if (str[0] == matrix[i])
			{
				if (solve(matrix, rows, cols, str, i / cols, i%cols, record))
					return true;
			}
		}
		return false;
	}
};

题目二:

题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

class Solution {
public:
	int NumS(int num)
	{
		int res = 0;
		while (num > 0)
		{
			res += num % 10;
			num = num / 10;
		}
		return res;
	}
	void solve(vector<bool>& record, const int& rows, const int& cols, int x, int y, int &count, const int& threshold)
	{
		if (x >= rows || x<0 || y >= cols || y<0) return;
		if (NumS(x) + NumS(y)>threshold || record[x*cols + y]) return;
		record[x*cols + y] = 1;
		count++;
		solve(record, rows, cols, x + 1, y + 0, count, threshold);
		solve(record, rows, cols, x - 1, y + 0, count, threshold);
		solve(record, rows, cols, x + 0, y + 1, count, threshold);
		solve(record, rows, cols, x + 0, y - 1, count, threshold);
	}
	int movingCount(int threshold, int rows, int cols)
	{
		vector<bool> record(rows*cols, 0);
		int count = 0;
		solve(record, rows, cols, 0, 0, count, threshold);
		return count;
	}
};

 

一个是寻找是否存在路径,一个是找可达区域范围大小。回溯时处理不同。

理解两道题的区别与不同点。

 

 

posted @ 2019-08-12 16:07  DH_HUSTer  阅读(16)  评论(0编辑  收藏  举报