51. Word Search

本文介绍了一个二维网格中查找单词的算法实现。通过深度优先搜索的方法,判断给定单词是否能够由相邻字母构成。文章详细解释了算法的具体实现,并提供了完整的C++代码示例。

Word Search

 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

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.

思路:深度优先搜索。注意每条路径搜索完之后,所有的 visited 重置为 false (未访问).

typedef pair<int, int> point;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};
bool dfs(vector<vector<char> > &board, string& word, int id, point p, vector<vector<bool> > &visited) {
    if(id == word.size()) return true;
    visited[p.first][p.second] = true;
    for(int i = 0; i < 4; ++i) {
        int x = p.first + dx[i], y = p.second +dy[i];
        if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || visited[x][y]) continue;
        if(board[x][y] == word[id] && dfs(board, word, id+1, point(x, y), visited)) 
            return true;
        visited[x][y] = false;
    }
    return false;
}
class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        if(word == "") return true;
        if(board.size() == 0 || board[0].size() == 0) return false;
        int row = board.size(), col = board[0].size();
        vector<vector<bool> > visited(row, vector<bool>(col, 0));
        for(int r = 0; r < row; ++r) {
            for(int c = 0; c < col; ++c) {
                if(board[r][c] == word[0] && dfs(board, word, 1, point(r,c), visited))
                        return true;
                visited[r][c] = false;
            }
        }
        return false;
    }
};

 

转载于:https://www.cnblogs.com/liyangguang1988/p/3954229.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值