力扣hot100 单词搜索 深度优先搜索 特殊字符判重

Problem: 79. 单词搜索
力扣hot100 单词搜索 深度优先搜索 特殊字符判重_第1张图片

Code

class Solution{
	int n, m;
	char[][] b;
	String word;
	int[] dx = { 1, 0, -1, 0 };
	int[] dy = { 0, 1, 0, -1 };

	public boolean exist(char[][] board, String word)
	{
		b = board;
		this.word = word;
		n = b.length;
		m = b[0].length;
//		以所有点作为起点来进行深度优先搜索
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++)
				if (dfs(i, j, 0))
					return true;
		return false;

	}

	/**
	 * @param x   行坐标
	 * @param y   列坐标
	 * @param idx 当前匹配到的字符下标
	 * @return
	 */
	private boolean dfs(int x, int y, int idx)
	{
		if (idx == word.length())// 最后一个字符 word[word.length()-1] 已经匹配成功
			return true;
		if (x >= 0 && x < n && y >= 0 && y < m)// 坐标合法,继续搜索
		{
			// 当前字符和当前应当匹配的 word[idx]相同才继续匹配,否则 false
			if (word.charAt(idx) == b[x][y])
			{
				for (int i = 0; i < 4; i++)//向4个方向匹配
				{
					char t = b[x][y];
					//相当于给当前位去重(设置一个不会出现在word中的特殊值)
					b[x][y] = '*';
					if (dfs(x + dx[i], y + dy[i], idx + 1))
						return true;//有一个方向搜索成功就 true
					b[x][y] = t;//恢复现场
				}
			}
		}
		return false;
	}
}

你可能感兴趣的:(力扣,hot100,leetcode,深度优先,算法)