标签:style class blog code http tar
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
.给一个二维字符数组,给一个字符串,问该二维数组是否包括该字符串。比方一个二维数组[ ABCE SFCS ADEE ]和字符串"ABCCED",这个就包括。解决问题,基本的关键是怎么解决在二维数组中查找方向,怎样来标识哪些是走过的。
class Solution { public: bool exist(vector<vector<char> > &board, string word) { int m = board.size(); if(m<=0) return false; int n = board[0].size(); for(int i=0; i<m; ++i) for(int j=0; j<n; ++j){ if(helper(0, word, i, j, board)) return true; } return false; } bool helper(int k, const string &word, int i, int j, vector<vector<char> > &board){ if(k==word.size()-1 && board[i][j]==word[k]) return true; if(board[i][j] != word[k]) return false; char temp = board[i][j]; // 走过的地方使用 '.' 来表示 board[i][j] = '.'; bool b1=false, b2=false, b3=false, b4=false; // board[i][j]的上面 if(i>0 && board[i-1][j]!='.') b1 = helper(k+1, word, i-1, j, board); // board[i][j]的以下 if(!b1 && i<board.size()-1 && board[i+1][j] != '.') b2 = helper(k+1, word, i+1, j, board); // board[i][j]的左面 if(!b1 && !b2 && j>0 && board[i][j-1] != '.') b3 = helper(k+1, word, i, j-1, board); // board[i][j]的右面 if(!b1 && !b2 && !b3 && j<board[0].size()-1 && board[i][j+1]!='.') b4 = helper(k+1, word, i, j+1, board); board[i][j] = temp; return b1 || b2 || b3 || b4; } };
[LeetCode] Word Search [37],布布扣,bubuko.com
标签:style class blog code http tar
原文地址:http://www.cnblogs.com/mfrbuaa/p/3809910.html