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.

 1 #include <vector>
 2 #include <string>
 3 #include <algorithm>
 4 #include <iostream>
 5 using namespace std;
 6 
 7 class Solution {
 8 public:
 9     bool exist(vector<vector<char>>& board, string word) {
10         int m = board.size();
11         int n = board[0].size();
12         
13         vector<vector<bool>> visited(m,vector<bool>(n,false));
14         for(int i=0;i<m;i++){
15             for(int j=0;j<n;j++){
16                 if(board[i][j] == word[0]){
17                     if(dfs(i,j,0,board,word,visited))
18                         return true;
19                 }
20             }
21         }
22         return false;
23     }
24 
25     bool dfs(int x,int y,int curr,vector<vector<char>>& board,
26         string& word,vector<vector<bool>>& visited){
27 
28         int m = board.size();
29         int n = board[0].size();
30 
31         if(curr == word.size())  return true;
32 
33         if(x<0 || x>=m || y<0 || y>=n) return false;
34 
35         if(board[x][y] != word[curr])  return false;
36 
37         if(visited[x][y] == true) return false;
38 
39         visited[x][y] = true;
40         bool ret= dfs(x, y+1, curr+1, board, word,visited) ||
41                dfs(x+1, y, curr+1, board, word,visited) ||
42                dfs(x, y-1, curr+1, board, word,visited) ||
43                dfs(x-1, y, curr+1, board, word,visited);
44         visited[x][y] = false;
45         return ret;
46     }
47 };
48 
49 int main()
50 {
51 
52     vector<vector<char>> board{{'a','a'}};
53     Solution s;
54     cout << s.exist(board, "aaa") << endl;
55     return 0;
56 
57 }
原文地址:https://www.cnblogs.com/wxquare/p/5011538.html