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

Problem: 79. 单词搜索
在这里插入图片描述

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;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值