LeetCode OJ: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 =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

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

简单的单词查找,在上下左右四个方向想dfs就可以了,代码如下,注意函数之间传递引用否则会超时的:

 1 class Solution {
 2 public:
 3     bool exist(vector<vector<char>>& board, string word) {
 4         if(!word.size())
 5             return false;
 6         int szHor = board.size();
 7         if(!szHor) return false;
 8         int szVer = board[0].size();
 9         if(!szVer) return false;
10         vector<vector<bool>> check(szHor, vector<bool>(szVer, false));
11         for(int i = 0; i < szHor; ++i){
12             for(int j = 0; j < szVer; ++j){
13                 if(board[i][j] == word[0]){
14                     check[i][j] = true;
15                     if(word.size() == 1 || search(word.substr(1), i, j, check, board))
16                         return true;
17                     check[i][j] = false;
18                 }
19             }
20         }
21         return false;
22     }
23 
24     bool search(string word, int i, int j, vector<vector<bool>> & check, vector<vector<char>> & board)
25     {
26         vector<vector<char>> direction{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
27         for(int k = 0; k < 4; ++k){
28             int ii = direction[k][0] + i;
29             int jj = direction[k][1] + j;
30             if(ii >= 0 && ii < board.size() && 
31                 jj >= 0 && jj < board[0].size() &&
32                 board[ii][jj] == word[0] && 
33                 check[ii][jj] == false){
34                 check[ii][jj] = true;
35                 if(word.size() == 1 || search(word.substr(1), ii, jj, check, board))
36                     return true;
37                 check[ii][jj] = false;
38             }
39         }
40         return false;
41     }
42 };
原文地址:https://www.cnblogs.com/-wang-cheng/p/4924374.html