标签:
This problem is somewhat tricky at first glance. However, the final implementation is fairly straight-forward.
The basic idea is, visiting every possible position (i, j) of board and find if starting from (i, j), the word exist in the board. For the word to exist from (i, j), two conditions should be satisfied:
Putting 1 and 2 together, we have the following code, which is fairly self-explanatory.
1 bool exist(vector<vector<char>> board, string word) { 2 for (int i = 0; i < board.size(); i++) 3 for (int j = 0; j < board[0].size(); j++) 4 if (isExist(board, word, i, j)) return true; 5 return false; 6 } 7 bool isExist(vector<vector<char>>& board, string word, int row, int col) { 8 if (row < 0 || row >= board.size() || col < 0 || col >= board[0].size() || board[row][col] != word[0]) 9 return false; 10 if (word.length() == 1) return true; 11 board[row][col] = ‘ ‘; 12 string tail = word.substr(1, word.length() - 1); 13 if (isExist(board, tail, row - 1, col) || isExist(board, tail, row + 1, col) || 14 isExist(board, tail, row, col - 1) || isExist(board, tail, row, col + 1)) 15 return true; 16 board[row][col] = word[0]; 17 return false; 18 }
Note that in the above code, in order to prevent visiting the same grid of board again, we modify the starting point of the grid and recover it again in line 11 and 16 respectively.
The above code is readable, though not fast enough. A simple trick to make it faster to pass a char* type instead of string to the isExist function.
1 bool exist(vector<vector<char>> board, string word) { 2 for (int i = 0; i < board.size(); i++) 3 for (int j = 0; j < board[0].size(); j++) 4 if (isExist(board, word.c_str(), i, j)) return true; 5 return false; 6 } 7 bool isExist(vector<vector<char>>& board, const char* word, int row, int col) { 8 if (row < 0 || row >= board.size() || col < 0 || col >= board[0].size() || board[row][col] != *word) 9 return false; 10 if (!(*(word + 1))) return true; 11 board[row][col] = ‘ ‘; 12 if (isExist(board, word + 1, row - 1, col) || isExist(board, word + 1, row + 1, col) || 13 isExist(board, word + 1, row, col - 1) || isExist(board, word + 1, row, col + 1)) 14 return true; 15 board[row][col] = *word; 16 return false; 17 }
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4550994.html