标签:
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
.class Solution { public: Solution(): isTrue(false) {} private: void dfs(vector<vector<char> > &board,string word, int x, int y, int index) { if(index == word.size()) { isTrue = true; return; } if(isTrue) return; if(x < 0 || x >= board.size()) return; if(y < 0 || y >= board[0].size()) return; if(board[x][y] != word[index]) return; board[x][y] = ‘#‘; dfs(board, word, x-1, y, index+1); dfs(board, word, x+1, y, index+1); dfs(board, word, x, y-1, index+1); dfs(board, word, x, y+1, index+1); board[x][y] = word[index]; } public: bool exist(vector<vector<char> > &board, string word) { if(board.empty() || board[0].empty()) return false; isTrue = false; int index = 0; for(int i=0; i<board.size(); i++) { for(int j=0; j<board[0].size(); j++) { if(!isTrue) dfs(board, word, i, j, index); } } return isTrue; } private: bool isTrue; };
标签:
原文地址:http://www.cnblogs.com/lxd2502/p/4484537.html