今天刷的这道题感觉还是有点难度的,下面就和大家分享一下经验吧!
题目如下:
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.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
题意分析:
给定一个二维平面(二维数组)和一个词,请判断该词(字符串)是否在二维平面中。该词可以通过二维平面中某个词的上下左右邻近词拼凑而成且二维数组每个元素只能用一次。
方法一(DFS递归法)
给定的二维数组就像一个平面,可以通过一个二维数组(d[4][2]={{1,0},{-1,0},{0,1},{0,-1}})实现向上下左右四个方向查询匹配。将二维数组中每一个数都作为起点与给定字符串做匹配,同时用一个与二维数组等长的bool 型visited数组来记录当前元素是否已被访问过(因为题目要求二维数组每个元素只能用一次)。如果二维数组board的当前字符和字符串word对应的字符相等,则对其上下左右四个邻字符分别调用DFS的递归函数,递归终止时只要返回true,即表明可以找到word,否则返回false,即不能找到word。
解题代码如下:
class Solution{
private:
int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
vector> visited;
int row,col;
bool isArea(int x, int y){
return x >= 0 && x < row && y >= 0 && y < col;
}
bool Findword(vector>& board, string& word, int index, int startx, int starty){
if (index == word.size()-1) return board[startx][starty] == word[index];
if (board[startx][starty] == word[index]) {
visited[startx][starty] = true;
for (int i = 0; i < 4; i++) {
int newx = startx+d[i][0];
int newy = starty+d[i][1];
if(isArea(newx, newy) && !visited[newx][newy] && Findword( board, word, index+1, newx, newy))
return true;
}
visited[startx][starty] = false;
}
return false;
}
public:
bool exist(vector>& board, string word) {
row = board.size();
assert(row > 0);
col = board[0].size();
visited = vector>(row, vector(col, false));
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[i].size(); j++) {
if(Findword(board, word, 0, i, j))
return true;
}
}
return false;
}
};
方法二(优化方法一)
这里可以不用创建bool型的visited数组,用过的元素直接置为'#',等递归调用完后需要将'#'重置为原来元素。
解题代码如下:
class Solution{
private:
int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int row,col;
bool isArea(int x, int y){
return x >= 0 && x < row && y >= 0 && y < col;
}
bool Findword(vector>& board, string& word, int index, int startx, int starty){
if (index == word.size()-1) return board[startx][starty] == word[index];
if (board[startx][starty] == word[index]) {
char temp = board[startx][starty];
board[startx][starty] = '#';
for (int i = 0; i < 4; i++) {
int newx = startx+d[i][0];
int newy = starty+d[i][1];
if(isArea(newx, newy) && board[newx][newy]!='#' && Findword( board, word, index+1, newx, newy))
return true;
}
board[startx][starty] = temp;
}
return false;
}
public:
bool exist(vector>& board, string word) {
row = board.size();
assert(row > 0);
col = board[0].size();
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[i].size(); j++) {
if(Findword(board, word, 0, i, j))
return true;
}
}
return false;
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。