Leetcode-79. Word Search

本文介绍了一个简单的WordSearch算法实现,该算法能够在二维网格中查找指定单词。通过深度优先搜索(DFS)的方式,从每个可能的位置开始尝试匹配单词,并确保同一字母单元格不会被重复使用。文章提供了完整的C++代码实现及解析。

79. Word Search

 
QuestionEditorial Solution
  My Submissions
 
  • Total Accepted: 98890
  • Total Submissions: 397019
  • Difficulty: Medium
  • Contributors: Admin

 

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.
 
思路:
四个方向挨个搜索即可,简单搜索题。
 
code:
 1 class Solution {
 2 public:
 3     int row,col;
 4     bool exist(vector<vector<char>>& board, string word) {
 5         row=board.size();
 6         if(row==0)
 7         return false;
 8         col=board[0].size();
 9 
10         vector<vector<int>> flag(row, vector<int>(col));
11         for(int i=0;i<board.size();i++)
12         {
13             for(int j=0;j<board[0].size();j++)
14             {
15                 //memset(flag,0,sizeof(flag));
16                 if(dfs(board,word,word.length(),i,j,flag))
17                 return true;
18             }
19         }
20         
21         return false;
22     }
23     
24     bool dfs(vector<vector<char>>& map,string word,int sum,int x,int y,vector<vector<int>>& flag)
25     {
26         if(sum==0)
27         return true;
28         bool res=false;
29         if(legal(x,y)&&map[x][y]==word[word.length()-sum]&&flag[x][y]!=1)
30         {
31             flag[x][y]=1;
32             res=res||dfs(map,word,sum-1,x+1,y,flag);
33             res=res||dfs(map,word,sum-1,x-1,y,flag);
34             res=res||dfs(map,word,sum-1,x,y-1,flag);
35             res=res||dfs(map,word,sum-1,x,y+1,flag);
36             flag[x][y]=0;
37         }
38         return res;
39     }
40     
41     bool legal(int x,int y)
42     {
43         if(x>=0&&x<row&&y>=0&&y<col)
44         return true;
45         return false;
46     }
47 };

 

转载于:https://www.cnblogs.com/hongyang/p/6061704.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值