您的位置:首页 > 其它

Leetcode-79. Word Search

2017-03-26 16:24 423 查看

题目

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 =

[

[‘A’,’B’,’C’,’E’],

[‘S’,’F’,’C’,’S’],

[‘A’,’D’,’E’,’E’]

]

word = “ABCCED”, -> returns true,

word = “SEE”, -> returns true,

word = “ABCB”, -> returns false.

求解给定字符串word,是否在字符矩阵board 中。要求word中相邻的两个字符,在board 中也是相邻字符,并且要求,board 中的同一字符,不能使用两次;

思路

使用dfs. 先在矩阵中找到word[0],若找到,就执行search函数继续查找。递归结束条件是 index == word.length(); 如果是超过边界或者board[i != word[index] 就return false。 为防止same letter cell may be used more than once, 要标记已经访问过的letter为 #. 每次递归结束以后还要还原以防影响下一次。

代码

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]) {
if(search(i, j, 0, word, board))
return true;
}
}
}
return false;
}

bool search(int i, int j, int index, string &word, vector<vector<char> >& board) {
if(index == word.size())
return true;
if(     i < 0 ||
j < 0 ||
i >= board.size()||
j >= board[0].size() ||
board[i][j] != word[index]) {
return false;
}
char c = board[i][j];
board[i][j] = '#';
bool rst =  search(i + 1, j, index + 1, word, board) ||
search(i, j + 1, index + 1, word, board) ||
search(i, j - 1, index + 1, word, board) ||
search(i - 1, j, index + 1, word, board);
board[i][j] = c;
return rst;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: