leetcode 56: Word Search
2013-01-27 09:48
330 查看
Word SearchApr
18 '12
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 =
word =
-> returns
word =
-> returns
word =
-> returns
uncompleted
18 '12
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.
uncompleted
class Position{ public: int x; int y; Position(int xx, int yy) : x(xx),y(yy){}; }; class Solution { public: bool exist(vector<vector<char> > &board, string word) { // Start typing your C/C++ solution below // DO NOT write int main() function if(word.size() ==0) return true; if(board.size()==0) return false; Solution::m = board.size(); Solution::n = board[0].size(); vector<bool> temp(n,false); vector<vector<bool> > flags(m, temp); for( int i=0; i<m; i++) { for( int j=0; j<n; j++) { if(board[i][j]==word[0]){ flags[i][j] = true; if( dfs( board, word, flags, 0, Position(i, j) ) ) return true; flags[i][j] = false; } } } return false; } private: int m; int n; bool dfs( vector<vector<char> > &board, string & word, vector<vector<bool> >& flags, int level,Position p ) { if( level == word.size()-1) return true; if( word[level] != board[p.x][p.y]) return false; for( int i=-1; i<=1; i++) { for( int j=-1; j<=1; j++) { if(i+j!=1 && i+j!=-1) continue; if( p.x+i>=0 && p.y+j>=0 && p.x+i<m && p.y+j<n && !flags[p.x+i][p.y+j] ) { flags[p.x+i][p.y+j] = true; if( dfs(board, word, flags, level+1, Position( p.x+i, p.y+j) ) ) return true; else flags[p.x+i][p.y+j] == false; } } } return false; } };
相关文章推荐
- leetcode 56: Word Search
- leetcode56,58 intervals merge
- LeetCode56 Merge Intervals
- LeetCode 079 Word Search
- LeetCode56——Merge Intervals
- leetcode,79. Word Search
- [LeetCode] Word Search
- 算法分析与设计课程——LeetCode刷题之 Word Search
- [Leetcode] #56 Merge Intervals
- Leetcode Word Search
- LeetCode - Word Search
- [LeetCode] Word Search
- Leetcode 56 Merge Intervals
- LeetCode 79. Word Search
- leetcode--Word Search
- leetcode 56 合并区间
- [Leetcode] Word Search
- 回溯之Leetcode79——Word Search
- LeetCode--Word Search
- [leetcode ] word search