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函数 private boolean canFind(char[][] board,int i,int j,String left,boolean[][] visited) ,从(i,j)出开始搜索串left,visited数组记录某个位置是否包含在当前搜索的路径中,因为每个字符只能被使用一次。

代码如下:

 public class Solution {
private boolean canFind(char[][] board,int i,int j,String left,boolean[][] visited){
//if we have found one path
if(left.equals(""))
return true; //look around point(i,j) see if we can find next char
char next = left.charAt(0);
if(i-1>=0 && !visited[i-1][j] && board[i-1][j]== next ){
visited[i-1][j] = true;
if(canFind(board, i-1, j, left.substring(1),visited))
return true;
visited[i-1][j]= false;
} if(j-1>=0 && !visited[i][j-1] && board[i][j-1]== next ){
visited[i][j-1] = true;
if(canFind(board, i, j-1, left.substring(1),visited))
return true;
visited[i][j-1]= false;
} if(i+1 < board.length && !visited[i+1][j] && board[i+1][j]== next ){
visited[i+1][j] = true;
if(canFind(board, i+1, j, left.substring(1),visited))
return true;
visited[i+1][j]= false;
} if(j+1 < board[0].length && !visited[i][j+1] && board[i][j+1]== next ){
visited[i][j+1] = true;
if(canFind(board, i, j+1, left.substring(1),visited))
return true;
visited[i][j+1]= false;
} return false;
}
public boolean exist(char[][] board, String word) {
if(word == null || word.length() == 0)
return true;
if(board.length == 0)
return false; int m = board.length;
int n = board[0].length;
char now = word.charAt(0);
boolean[][] visited = new boolean[m][n]; //search board for our first char in word
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j ++){
if(board[i][j]== now ){
visited[i][j]= true;
if(canFind(board, i, j, word.substring(1),visited))
return true;
visited[i][j]= false;
}
}
} return false;
}
}

最新文章

  1. 【BZOJ1662】[Usaco2006 Nov]Round Numbers 圆环数 数位DP
  2. HDOJ 2444 The Accomodation of Students
  3. 关于jquery中 跳出each循环的方法
  4. spider autohome (1)
  5. i++和++i的区别
  6. GitHub-更新数据
  7. c++迭代器(iterator)详解
  8. BestCoder Round #85 sum
  9. 关于全局变量和函数,在其他类中调用问题,extern关键字
  10. 【转】Android手机客户端关于二维码扫描的源码--不错
  11. grunt 的安装和简单使用
  12. C# 高性能 TCP 服务的多种实现方式
  13. HTML5_canvas_填充文本,描边文本
  14. 一步步学会用docker部署应用(nodejs版)
  15. LeetCode算法题-Longest Palindrome(五种解法)
  16. Java多线程(五)——线程等待与唤醒
  17. 24种java设计模式总结和目录
  18. Windows 动态链接库DLL使用
  19. 686. Repeated String Match
  20. Word 如何实现表格快速一分为二

热门文章

  1. IOS7下,AVAudioRecorder需要注意的一点
  2. C#常见的概念阐述
  3. SQL Server中LIKE和PATINDEX的用法
  4. android收起软键盘
  5. CentOs上搭建nginx
  6. IDC机房带宽突然暴涨问题!
  7. Java并发编程(一)学习大纲
  8. 交易应用及网站驱动不兼容Windows 10的解决方案
  9. 将普通用户添加至sudoers列表
  10. php 判断数组中是否有重复的值