[Leetcode 69] 79 Word Search

Problem:

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.

Analysis:

This is a typical DFS problem. The possible start state is each character of the given board.  But the possible intermediate state can only be forwarding a more step from the current state into one of four directions (up, down, right, left).

Some of the optimizations are

1. in-place tracking of whether a position is visited (change b[i][j] into '#' to indicate it has been visited)

2. directions[][] array uaeage to reduce the code

Code:

 1 class Solution {
 2 public:
 3     bool exist(vector<vector<char> > &board, string word) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         w = word;
 7         row = board.size();
 8         col = board[0].size();
 9 
10         bool e = false;
11 
12         string ww = "";
13         for (int i=0; i<row; i++) {
14             for (int j=0; j<col; j++) {
15                 if (board[i][j] == word[0]) {
16                     ww.push_back(board[i][j]);
17                     board[i][j] = '#';
18                     dfs(ww, i, j, board, e);
19                     board[i][j] = word[0];
20                     ww.erase(ww.end()-1);
21                     if (e) return true;
22                 }
23             }
24         }
25         
26         return false;
27     }
28     
29 private:
30     string w;
31     int col, row;
32     int direct[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
33 
34     bool isValid(int x, int y, vector<vector<char> > &b) 
35     {
36         return ((x>=0 && x<row) && (y>=0 && y<col) && (b[x][y] != '#'));
37     }
38     
39     void dfs(string s, int i, int j, vector<vector<char> > &b, bool &res) 
40     {
41         if (s[s.length()-1] != w[s.length()-1]) return ;
42 
43         if (s.length() == w.length()) {
44             if (s == w) 
45                 res = true;
46 
47             return ;
48         }
49 
50         for (int k=0; k<4; k++) {
51             int ii = i + direct[k][0];
52             int jj = j + direct[k][1];
53             
54             if (isValid(ii, jj, b)) {
55                 s.push_back(b[ii][jj]);
56                 b[ii][jj] = '#';
57                 dfs(s, ii, jj, b, res); 
58                 b[ii][jj] = s.back();
59                 s.erase(s.end()-1);
60             }
61             
62             if (res) return ;
63         }
64         
65         return ;
66     }
67 };
View Code
原文地址:https://www.cnblogs.com/freeneng/p/3201965.html