Leetcode:Word Search 字符矩阵中查找单词

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.

 

解题分析:

深度搜索,首先找到与单词首字母相等的字符,然后在该字符的上下左右做深度搜索

搜索过程中,注意对当前横坐标和纵坐标做边界检查,即剪枝

另外,我们需要开设一个同等大小的flag矩阵,标记当前是否已经访问过

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        int row = board.size();
        if (row == 0) return false;
        int col = board.at(0).size();
        vector<vector<bool> > visited(row, vector<bool>(col, false));
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < col; ++j) {
                if (dfs(board, i, j, word, 0, visited) == true) {
                    return true;
                }
            }
        }
        return false;
    }
    
    
    bool dfs(const vector<vector<char> >& board, int iRow, int iCol, string word, int index, vector<vector<bool> >& visited) {
        if (index == word.size())  return true;
        int row = board.size();
        int col = board.at(0).size();
        
        if (iRow < 0 || iRow >= row || iCol < 0 || iCol >= col)  return false;
        
        if (board.at(iRow).at(iCol) != word.at(index))  return false;
        
        if (visited.at(iRow).at(iCol) == true)  return false;
        visited.at(iRow).at(iCol) = true; bool ret = dfs(board, iRow - 1, iCol, word, index+1, visited) || 
                   dfs(board, iRow + 1, iCol, word, index+1, visited) ||
                   dfs(board, iRow, iCol - 1, word, index+1, visited) ||
                   dfs(board, iRow, iCol + 1, word, index+1, visited);
        visited.at(iRow).at(iCol) = false; return ret;
    }
};

 

你可能感兴趣的:(LeetCode)