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
.
fk! 被两个问题卡住了, 一个是要先帮search函数找到入口,开始我偷懒想试图让程序自己找入口,结果就悲剧了,还找了半天bug,还有一个问题就是已经得到函数结果要尽快return,因为是递归函数,不尽快return的话,后面还会继续递归,然后就华丽丽的超时了。
1 class Soluton { 2 public: 3 bool search(vector<vector<char> > &board, string &word, vector<vector<bool> > &mask, int idx, int x, int y) { 4 if (word[idx] == board[x][y]) { 5 ++idx; 6 if (idx == word.length()){ 7 return true; 8 } 9 } else { 10 return false; 11 } 12 mask[x][y] = false; 13 bool flag1, flag2, flag3, flag4; 14 flag1 = flag2 = flag3 = flag4 = false; 15 if (y + 1 < board[0].size() && mask[x][y+1] && board[x][y+1] == word[idx]) { 16 if (search(board, word, mask, idx, x, y + 1)) 17 return true; 18 } 19 if (x + 1 < board.size() && mask[x+1][y] && board[x+1][y] == word[idx]) { 20 if (search(board, word, mask, idx, x + 1, y)) 21 return true; 22 } 23 if (x - 1 >= 0 && mask[x-1][y] && board[x-1][y] == word[idx]) { 24 if (search(board, word, mask, idx, x - 1, y)) 25 return true; 26 } 27 if (y - 1 >= 0 && mask[x][y-1] && board[x][y-1] == word[idx]) { 28 if (search(board, word, mask, idx, x, y - 1)) 29 return true; 30 } 31 mask[x][y] = true; 32 return false; 33 } 34 35 bool exist(vector<vector<char> > &board, string word) { 36 vector<vector<bool> > mask(board.size(), vector<bool>(board[0].size(), true)); 37 if (board.size() < 1) return false; 38 for (int i = 0; i <board.size(); ++i) { 39 for (int j = 0; j < board[0].size(); ++j) { 40 if (board[i][j] == word[0] && search(board, word, mask, 0, i, j)) { 41 return true; 42 } 43 } 44 } 45 return false; 46 } 47 };
[Leetcode] Word Search,布布扣,bubuko.com
原文:http://www.cnblogs.com/easonliu/p/3647880.html