标签:style blog color io os ar for strong sp
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
.
主要思路,通过递归深搜,board中每个元素都作为起点,从board中起点开始比较word中对应的字符是否相等,如果相等,则标记该元素已被搜过,并依次搜索上下左右相邻的元素,在下次递归的时候又与word中对应的字符比较;不然则之间返回false
1 class Solution { 2 public: 3 bool exist(vector<vector<char> > &board, string word) { 4 int rows = board.size(); 5 int cols = board[0].size(); 6 if( rows < 1 || cols < 1 || word.empty() ) return false; 7 for(int i=0; i<rows; ++i) //依次让board中每个元素作为起点 8 for(int j=0; j<cols; ++j) 9 if( dfs(board, word, i, j, 0) ) return true; 10 return false; 11 } 12 13 bool dfs(vector<vector<char> > &board, string& word, int i, int j, int k) { 14 if( board[i][j] != word[k] ) return false; //当前board位置的元素与word[k]不等,可回溯了 15 if( k == word.length()-1 ) return true; //说明word已经被比较完 16 char ch = board[i][j]; //备份原来位置的值,以便回溯 17 board[i][j] = ‘#‘; 18 if( i>0 && board[i-1][j] != ‘#‘ && dfs(board, word, i-1, j, k+1) ) //向上 19 return true; 20 if( i<board.size()-1 && board[i+1][j] != ‘#‘ && dfs(board, word, i+1, j, k+1) ) //向下 21 return true; 22 if( j>0 && board[i][j-1] != ‘#‘ && dfs(board, word, i, j-1, k+1) ) //向左 23 return true; 24 if( j<board[i].size()-1 && board[i][j+1] != ‘#‘ && dfs(board, word, i, j+1, k+1) ) //向右 25 return true; 26 board[i][j] = ch; //回复原来的值 27 return false; 28 } 29 };
标签:style blog color io os ar for strong sp
原文地址:http://www.cnblogs.com/bugfly/p/4009793.html