个人主页:元清加油_【C++】,【C语言】,【数据结构与算法】-CSDN博客
个人专栏
力扣递归算法题
【C++】? ??
??????http://t.csdnimg.cn/6AbpV
数据结构与算法
?????http://t.csdnimg.cn/hKh2l
前言:这个专栏主要讲述递归递归、搜索与回溯剪枝算法,所以下面题目主要也是这些算法做的 ?
我讲述题目会把讲解部分分为3个部分:
1、题目解析
2、算法原理思路讲解
3、代码实现
题目链接:单词搜索
题目
给定一个?m x n
?二维字符网格?board
?和一个字符串单词?word
?。如果?word
?存在于网格中,返回?true
?;否则,返回?false
?。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" 输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" 输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" 输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
?和?word
?仅由大小写英文字母组成?
二、设计代码
(1)全局变量
string Word;
bool visit[10][16];
int dx[4] = { 0, 0, -1, 1 };
int dy[4] = { 1, -1, 0, 0 };
(2)设计递归函数
bool dfs(vector<vector<char>>& board, int row, int col, int pos);
递归过程
class Solution {
public:
string Word;
bool visit[10][16];
int dx[4] = { 0, 0, -1, 1 };
int dy[4] = { 1, -1, 0, 0 };
bool dfs(vector<vector<char>>& board, int row, int col, int pos)
{
if (pos == Word.size())
{
return true;
}
int m = board.size();
int n = board[0].size();
for (int i = 0 ; i < 4; i++)
{
int x = row + dx[i], y = col + dy[i];
if (x >= 0 && x < m && y >= 0 && y < n && !visit[x][y] && board[x][y]== Word[pos])
{
visit[x][y] = true;
if (dfs(board, x, y,pos + 1))
return true;
visit[x][y] = false;
}
}
return false;
}
bool exist(vector<vector<char>>& board, string word)
{
Word = word;
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[i].size(); j++)
{
if (board[i][j] == word[0])
{
visit[i][j] = true;
if (dfs(board, i, j, 1) == true)
return true;
visit[i][j] = false;;
}
}
}
return false;
}
};