首页 > 代码库 > Word Search
Word Search
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.
思路:本题使用DFS求解即可。下面的解法假设输入word中不会包含‘#’这样的字符。
1 class Solution { 2 public: 3 bool exist( vector<vector<char>> &board, string word ) { 4 if( board.empty() ) { return word.empty(); } 5 rows = board.size(), cols = board[0].size(), slen = word.length(); 6 for( int i = 0; i < rows; ++i ) { 7 for( int j = 0; j < cols; ++j ) { 8 if( board[i][j] == word[0] && DFS( i, j, board, 0, word ) ) { return true; } 9 }10 }11 return false;12 }13 private:14 bool DFS( int i, int j, vector<vector<char>>& board, int index, const string& word ) {15 if( ++index == slen ) { return true; }16 board[i][j] = ‘#‘;17 if( i > 0 && board[i-1][j] == word[index] && DFS( i-1, j, board, index, word ) ) {18 board[i][j] = word[index-1];19 return true;20 }21 if( i < rows-1 && board[i+1][j] == word[index] && DFS( i+1, j, board, index, word ) ) {22 board[i][j] = word[index-1];23 return true;24 }25 if( j > 0 && board[i][j-1] == word[index] && DFS( i, j-1, board, index, word ) ) {26 board[i][j] = word[index-1];27 return true;28 }29 if( j < cols-1 && board[i][j+1] == word[index] && DFS( i, j+1, board, index, word ) ) {30 board[i][j] = word[index-1];31 return true;32 }33 board[i][j] = word[index-1];34 return false;35 }36 int rows, cols, slen;37 };
Word Search
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。