现在的位置: 首页 > 综合 > 正文

LeetCode题解:Word Search

2018年03月31日 ⁄ 综合 ⁄ 共 1310字 ⁄ 字号 评论关闭

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.

思路:

题目没什么特别的难度,就是做一个深搜即可。

题解:

class Solution {
public:
    typedef vector<vector<char>> board_t;
    
    int N, M;
    board_t used_mark;
    
    bool navigate(const board_t& board, const string& word,
                  int board_i, int board_j, int word_offset)
    {
        if (board_i < 0 || board_j < 0 ||
                board_i >= N || board_j >= M ||
                used_mark[board_i][board_j] != 0 ||
                board[board_i][board_j] != word[word_offset])
            return false;
    
        if (word_offset == word.size() - 1)
            return true;
    
        used_mark[board_i][board_j] = 1;
    
        if ( navigate(board, word, board_i, board_j - 1, word_offset + 1) ||
                navigate(board, word, board_i, board_j + 1, word_offset + 1) ||
                navigate(board, word, board_i - 1, board_j , word_offset + 1) ||
                navigate(board, word, board_i + 1, board_j , word_offset + 1) )
            return true;
    
        used_mark[board_i][board_j] = 0;
        return false;
    }
    
    bool exist(const board_t& board, const string& word)
    {
        N = board.size();
        M = board[0].size();
    
        used_mark.resize(N);
        for (auto & m : used_mark)
        {
            m.resize(M);
            fill(begin(m), end(m), 0);
        }
    
        for (auto i = 0; i < N; ++i)
            for (auto j = 0; j < M; ++j)
                if (board[i][j] == word[0])
                    if (navigate(board, word, i, j, 0))
                        return true;
    
        return false;
    }
};

抱歉!评论已关闭.