Word Search
来源:互联网 发布:mac 双重认证 编辑:程序博客网 时间:2024/06/05 20:48
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 =
[ ["ABCE"], ["SFCS"], ["ADEE"]]word =
"ABCCED"
, -> returns true
,word =
"SEE"
, -> returns true
,word =
"ABCB"
, -> returns false
.dfs的Java代码
public class Solution { public boolean exist(char[][] board, String word) { if(word==null) return true; if(board==null || board.length==0) return false; int m=board.length; int n=board[0].length; boolean [][]vis=new boolean[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(dfs(i,j,0,board,word,vis)) return true; } } return false; } public boolean dfs(int i,int j,int k,char[][]board, String word,boolean [][]vis){ if(k==word.length()) return true; if(i<0 || j<0 || i>=board.length || j>=board[0].length) return false; if(vis[i][j]) return false; if(word.charAt(k)!=board[i][j]) return false; vis[i][j]=true; boolean res=false; res=dfs(i+1,j,k+1,board,word,vis)|| dfs(i-1,j,k+1,board,word,vis)|| dfs(i,j+1,k+1,board,word,vis)|| dfs(i,j-1,k+1,board,word,vis); vis[i][j]=false; return res; }}
C++ 复习
class Solution {public: bool exist(vector<vector<char> > &board, string word) { int m=board.size(); int n=board[0].size(); vector< vector<bool> > vis(m, vector<bool>(n,false) ); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(dfs(i,j,0,board,word,vis)) return true; } } return false; } bool dfs(int x,int y,int k,vector<vector<char> > &board, string &word,vector< vector<bool> > &vis){ if(k==word.size()) return true; if(x<0 || y<0 || x>=board.size() || y>=board[0].size()) return false; if(vis[x][y]) return false; if(word[k]!=board[x][y]) return false; vis[x][y]=true; bool res=dfs(x+1,y,k+1,board,word,vis)|| dfs(x-1,y,k+1,board,word,vis)|| dfs(x,y+1,k+1,board,word,vis)|| dfs(x,y-1,k+1,board,word,vis); vis[x][y]=false; return res; }};
0 0
- Word Search
- Word Search
- word search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- 编程之美2.3: 寻找发帖水王
- socket编程之三:socket网络编程中的常用函数
- Android 安全机制概述
- 以互联网思维做好客户端软件
- phpinfo中Loaded Configuration File 为 none
- Word Search
- 安卓数据保存——保存到Preference
- ssh无密码登录总是失败的问题
- PHP采集程序原理分析篇
- C++中explicit关键字的作用
- linux下使用libxml2实现对xml文件的读取及查询
- 关于Java集合类迭代变量的修改
- 使用Freescale DZ60控制单个或多个DS18B20
- 1059. Prime Factors (25)