题目:
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
.
代码:
class Solution { public: bool exist(vector<vector<char> >& board, string word) { vector<vector<bool> > visited; for ( size_t i = 0; i < board.size(); ++i ) { vector<bool> tmp(board[i].size(),false); visited.push_back(tmp); } for ( int i = 0; i < board.size(); ++i ) { for ( int j = 0; j < board[i].size(); ++j ) { if (Solution::dfs(board, visited, i, j, word, 0)) return true; } } return Solution::dfs(board, visited, 0, 0, word, 0); } static bool dfs( vector<vector<char> >& board, vector<vector<bool> >& visited, int i, int j, string& word, int curr ) { if ( curr==word.size() ) return true; if ( i<0 || i==board.size() || j<0 || j==board[i].size() ) return false; if ( visited[i][j] ) return false; if ( board[i][j]!=word[curr] ) return false; if ( board[i][j]==word[curr] ) { visited[i][j] = true; if ( Solution::dfs(board, visited, i, j+1, word, curr+1)) return true; if ( Solution::dfs(board, visited, i+1, j, word, curr+1)) return true; if ( Solution::dfs(board, visited, i, j-1, word, curr+1)) return true; if ( Solution::dfs(board, visited, i-1, j, word, curr+1)) return true; } visited[i][j] = false; return false; } };
tips:
好好领悟一下dfs吧。。。
1. 这道题在主程序中有一个循环,如果一旦发现word的起点,就从这个位置开始dfs,看能否返回结果。
2. dfs的过程跟模板一样。
shit
============================================
第二次过这道题,逻辑清晰了很多,修正了两个笔误bug,AC了。
class Solution { public: bool exist(vector<vector<char> >& board, string word) { for ( int i=0; i<board.size(); ++i ) { for ( int j=0; j<board[i].size(); ++j ) { if ( board[i][j]==word[0] ) { board[i][j] = '#'; if ( Solution::dfs(board, i, j, word.substr(1,word.size()-1)) ) return true; board[i][j] = word[0]; } } } return false; } static bool dfs( vector<vector<char> >& board, int i, int j, string word) { if ( word.size()==0 ) return true; // left if ( j-1>=0 && board[i][j-1]==word[0] ) { board[i][j-1] = '#'; if (Solution::dfs(board, i, j-1, word.substr(1,word.size()-1)) ) return true; board[i][j-1] = word[0]; } // right if ( j+1<board[0].size() && board[i][j+1]==word[0] ) { board[i][j+1] = '#'; if (Solution::dfs(board, i, j+1, word.substr(1,word.size()-1)) ) return true; board[i][j+1] = word[0]; } // up if ( i-1>=0 && board[i-1][j]==word[0] ) { board[i-1][j] = '#'; if (Solution::dfs(board, i-1, j, word.substr(1,word.size()-1)) ) return true; board[i-1][j] = word[0]; } // down if ( i+1<board.size() && board[i+1][j]==word[0] ) { board[i+1][j] = '#'; if (Solution::dfs(board, i+1, j, word.substr(1,word.size()-1)) ) return true; board[i+1][j] = word[0]; } return false; } };
第二次的代码,比第一次过的代码还优化了额外空间结构。O(1)额外空间。