leetCode练习(79)
来源:互联网 发布:好看的手机壁纸软件 编辑:程序博客网 时间:2024/05/19 04:53
题目:Word Search
难度:medium
问题描述:
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
.解题思路:走迷宫一样,问有没有一条路径等于word。对每一个值为word[0]的节点使用DFS,若有满足的路径即可返回true。使用一个Boolean[][] count记录是否被走过。另一个思路是使用BFS,但BFS同时有多条路径在走,需要大量count,得不偿失。
DFS代码如下:
public class m_79_WordSearch {public boolean exist(char[][] board, String word) { for(int i=0;i<board.length;i++){ for(int j=0;j<board[0].length;j++){ if(board[i][j]==word.charAt(0)){ if(DFS(board,i,j,word,new boolean[board.length][board[0].length])){ return true; } } } } return false; }private boolean DFS(char[][] board, int x,int y,String word, boolean[][] count) {if(board[x][y]!=word.charAt(0)){return false;}if(word.length()==1){return true;}count[x][y]=true;if(x>0&&!count[x-1][y]){if(DFS(board,x-1,y,word.substring(1),count)){return true;}}if(x<board.length-1&&!count[x+1][y]){if(DFS(board,x+1,y,word.substring(1),count)){return true;}}if(y>0&&!count[x][y-1]){if(DFS(board,x,y-1,word.substring(1),count)){return true;}}if(y<board[0].length-1&&!count[x][y+1]){if(DFS(board,x,y+1,word.substring(1),count)){return true;}}count[x][y]=false;return false;}}
0 0
- leetCode练习(79)
- leetCode练习(7)
- leetCode练习(9)
- leetCode练习(2)
- leetCode练习(14)
- leetCode练习(3)
- leetCode练习(4)
- leetCode练习(19)
- leetCode练习(18)
- leetCode练习(5)
- leetCode练习(15)
- leetCode练习(20)
- leetCode练习(21)
- leetCode练习(16)
- leetCode练习(17)
- leetCode练习(11)
- leetCode练习(24)
- leetCode练习(22)
- 在Unity中构建健壮的单例模式(Singleton)
- Mysql:using,having,as关键字
- Python学习笔记(2)
- ActiveMQ SSL应用之一 整体介绍
- 超级账本PBFT(拜占庭容错)算法详解
- leetCode练习(79)
- Selenium+Python浏览器调用:Firefox
- Python——基本的序列和映射规则
- 组合查询
- java集合框架
- TCP&UDP协议
- JDBC编程——MySQL
- PHP面向对象_对象串行化serialize(),__sleep(),__wakeup()
- hdu 1002 A + B Problem II