LeetCode 79. Word Search
来源:互联网 发布:git ssh 端口 编辑:程序博客网 时间:2024/06/03 15:53
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
.分析:
回溯+深度搜索,用数组存放四个方向,依次进行深搜
class Solution {public: bool exist(vector<vector<char>>& board, string word) { int n=board.size(),m; if(n>0) m=board[0].size(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(board[i][j]==word[0]){ memset(vis,0,sizeof(vis)); vis[i][j]=1; dfs(1,i,j,board,word,n,m); if(flag) return flag; } } } return false; }private: int dic[4][2]={1,0,-1,0,0,1,0,-1}; int vis[1005][1005]; bool flag=false; void dfs(int index,int r,int l,vector<vector<char>>& board, string word,int n,int m){ if(flag) return; if(index==word.length()){ flag=true; return; } for(int i=0;i<4;i++){ int rr=dic[i][0]+r; int ll=dic[i][1]+l; if(rr<0||rr>=n||ll<0||ll>=m||vis[rr][ll]==1||board[rr][ll]!=word[index]) continue; vis[rr][ll]=1; dfs(index+1,rr,ll,board,word,n,m); vis[rr][ll]=0; } } };
阅读全文
2 0
- LeetCode 79. Word Search
- [LeetCode]79.Word Search
- LeetCode --- 79. Word Search
- [Leetcode] 79. Word Search
- [leetcode] 79.Word Search
- 【leetcode】79. Word Search
- [LeetCode]79. Word Search
- 79. Word Search LeetCode
- leetcode 79. Word Search
- LeetCode 79. Word Search
- LeetCode 79. Word Search
- leetcode 79. Word Search
- LeetCode *** 79. Word Search
- [leetcode] 79. Word Search
- LeetCode-79.Word Search
- Leetcode 79. Word Search
- LeetCode - 79. Word Search
- [LeetCode] 79. Word Search
- SQL中的五种数据类型
- MVC分层架构
- gson解析对象数组
- 辗转相除法
- 算法提高 ADV-231 12-2扑克排序
- LeetCode 79. Word Search
- FFmpeg音频转码总结
- 在线预览PDF
- PHP中级工程师笔试题二
- 原始问题与对偶问题
- Gazeboard仿真环境搭建
- 59. Spiral Matrix II && 54. Spiral Matrix
- Java中自定义异常的使用
- Camera_视屏拍摄和拍摄图片与MediaRecorder之录制音频