Leetcode79.Word_Search

回溯法
时间复杂度O(NMK)(在长N宽M的矩阵内搜索长为K的单词)
C++代码:

class Solution {
	vector<vector<char>> a;
	vector<vector<bool>> use;
	int n;
	int m;
public:
	const int wx[4] = { 0,0,-1,1 };
	const int wy[4] = { -1,1,0,0 };
	bool visit(int x, int y, int step, string word) {
		if (step == word.length())
		{
			return true;
		}
		use[x][y] = false;
		for (int i = 0; i < 4; i++)
		{
			int xx = x + wx[i];
			int yy = y + wy[i];
			if (xx >= 0 && xx < n&&yy >= 0 & yy < m&&use[xx][yy] && a[xx][yy] == word[step]) {
				if (visit(xx, yy, step + 1, word))
					return true;
			}
		}
		use[x][y] = true;
		return false;
	}
	bool exist(vector<vector<char>>& board, string word) {
		a = board;
		n = a.size();
		m = a[0].size();
		if (a.size() == 0) {
			return false;
		}
		if (a[0].size() == 0) {
			return false;
		}
		if (word.length() == 0) {
			return true;
		}
		use.resize(n, vector<bool>(m, true));
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (a[i][j] == word[0]) {
					if (visit(i, j, 1, word))
						return true;
				}
			}
		}
		return false;
	}
};

猜你喜欢

转载自blog.csdn.net/qq_42263831/article/details/83715895