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
,"SEE"
,
-> returns true
,"ABCB"
,
-> returns false
.
基本思路:
1. 对棋盘每个点进行深度优搜索。
2. 传统Ascii码,只会用7bit,最高bit为0. 故可用此bit位,复用作访问标志位。
class Solution { public: bool exist(vector<vector<char> > &board, string word) { if (board.empty() || board[0].empty()) return false; for (int i=0; i<board.size(); i++) { for (int j=0; j<board[0].size(); j++) { if (exist(board, word, 0, i, j)) return true; } } return false; } bool exist(vector<vector<char> >&board, const string &word, int index, int x, int y) { if (index == word.size()) return true; if (x<0 || y<0 || x==board.size() || y==board[0].size()) return false; if (board[x][y] != word[index]) return false; board[x][y] ^= 128; const bool existed = exist(board, word, index+1, x, y+1) || exist(board, word, index+1, x, y-1) || exist(board, word, index+1, x+1, y) || exist(board, word, index+1, x-1, y); board[x][y] ^= 128; return existed; } };
原文地址:http://blog.csdn.net/elton_xiao/article/details/45039107