79, Word Search

本文介绍了一种算法,用于在一个二维字符网格中查找指定的单词。该算法采用深度优先搜索(DFS)结合回溯的方法,检查网格中是否存在按相邻方向构成目标单词的路径。通过实例演示了如何实现这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,

word = "ABCB", -> returns false.

代码:

class Solution {
public:
	bool exist(vector<vector<char>>& board, string word) {
		int width = board[0].size();
		int height = board.size();
		vector<vector<bool>> used(height, vector<bool>(width, false));
		
		bool res = false;
		for (int i = 0; i < board.size(); i++){
			for (int j = 0; j < board[0].size(); j++){
				if (board[i][j] == word[0])
				    used[i][j] = true;
					helper(board, 0, word, res, i, j, 0, used);
					used[i][j] = false;//记住, 这里的used也要回溯。
			}
		}
		return res;
	}
	// 这里的direction参数可以省略
	void helper(vector<vector<char>>& board, int start, string& word, bool& res, int x, int y, int direction, vector<vector<bool>>& used){
		if(res) return;//这一句太重要了, DFS + Backtracking 在搜索到第一个结果时,要break;
		if (board[x][y] != word[start]) return;
		if (start == word.size() - 1){
			res = true;
			return;
		}

		int width = board[0].size();
		int height = board.size();
		if (direction != 2 && y != 0 && !used[x][y - 1])//left 1 
		{
			used[x][y - 1] = true;
			helper(board, start + 1, word, res, x, y - 1, 1, used);
			used[x][y - 1] = false;
		}

		if (direction != 1 && y != width - 1 && !used[x][y + 1])//right 2
		{
			used[x][y + 1] = true;
			helper(board, start + 1, word, res, x, y + 1, 2, used);
			used[x][y + 1] = false;
		}

		if (direction != 4 && x != 0 && !used[x - 1][y])//down 3
		{
			used[x - 1][y] = true;
			helper(board, start + 1, word, res, x - 1, y, 3, used);
			used[x - 1][y] = false;
		}

		if (direction != 3 && x != height - 1 && !used[x + 1][y])//up 4
		{
			used[x + 1][y] = true;
			helper(board, start + 1, word, res, x + 1, y, 4, used);
			used[x + 1][y] = false;
		}
	}
};
优化代码:

public class Solution {
public boolean exist(char[][] board, String word) {
    for(int i = 0; i < board.length; i++)
        for(int j = 0; j < board[0].length; j++){
            if(exist(board, i, j, word, 0))
                return true;
        }
    return false;
}
private boolean exist(char[][] board, int i, int j, String word, int ind){
    if(ind == word.length()) return true;
    if(i > board.length-1 || i <0 || j<0 || j >board[0].length-1 || board[i][j]!=word.charAt(ind))
        return false;
    board[i][j]='*';
    boolean result =    exist(board, i-1, j, word, ind+1) ||
                        exist(board, i, j-1, word, ind+1) ||
                        exist(board, i, j+1, word, ind+1) ||
                        exist(board, i+1, j, word, ind+1);
    board[i][j] = word.charAt(ind);
    return result;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值