LeetCode 79. Word Search

本文介绍了一个二维网格中查找单词的问题及解决方案。通过深度优先搜索(DFS)策略,从每个可能的起点开始遍历网格,检查目标单词是否能由相邻字母组成。文章提供了两种不同的C++实现方法。

1. 题目描述

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.

2. 解题思路

拿到这个问题首先想到的是 DFS 搜索, 由此可以很容易的给出代码

3. code

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        bool ret = false;
        for (int i = 0; i != board.size(); i++){
            for (int j = 0; j != board[0].size(); j++){
                if (board[i][j] == word[0]){
                    ret = _exist(board, word, 0, i, j);
                    if (ret)
                        return true;
                }                   
            }
        }
        return ret;
    }

private:
    bool _exist(vector<vector<char>>& board, string word, int depth, int row, int col){
        if (depth == word.size())
            return true;

        if (row >= board.size() || col >= board[0].size() || word[depth] != board[row][col])
            return false;       

        char tmp = board[row][col];
        board[row][col] = 0;
        bool ret = _exist(board, word, depth + 1, row + 1, col);
        if (!ret)
            ret = _exist(board, word, depth + 1, row - 1, col);
        if (!ret)
            ret = _exist(board, word, depth + 1, row, col + 1);
        if (!ret)
            ret = _exist(board, word, depth + 1, row, col - 1);
        board[row][col] = tmp;

        return ret;
    }
};

4. 大神解法

一样的思路

public boolean exist(char[][] board, String word) {
    char[] w = word.toCharArray();
    for (int y=0; y<board.length; y++) {
        for (int x=0; x<board[y].length; x++) {
            if (exist(board, y, x, w, 0)) return true;
        }
    }
    return false;
}

private boolean exist(char[][] board, int y, int x, char[] word, int i) {
    if (i == word.length) return true;
    if (y<0 || x<0 || y == board.length || x == board[y].length) return false;
    if (board[y][x] != word[i]) return false;
    board[y][x] ^= 256;
    boolean exist = exist(board, y, x+1, word, i+1)
        || exist(board, y, x-1, word, i+1)
        || exist(board, y+1, x, word, i+1)
        || exist(board, y-1, x, word, i+1);
    board[y][x] ^= 256;
    return exist;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值