Medium 79题 Word Search
来源:互联网 发布:淘宝开店客服的子账号 编辑:程序博客网 时间:2024/05/16 15:06
Question:
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
.Solution:
public class Solution { public boolean exist(char[][] board, String word) { boolean[][] b; char[] w = word.toCharArray(); for(int i=0;i<=board.length-1;i++) { for(int j=0;j<=board[0].length-1;j++) { if(board[i][j]==w[0]) { b=new boolean[board.length][board[0].length]; if(search(board,i,j,b,0,w)){ return true; } } } } return false; } //根据首字母的i,j位置查找word private boolean search(char[][] board,int i,int j,boolean[][] b,int index,char[] w){ if(board[i][j] != w[index]){//字符不相等。返回false return false; } if(index == w.length - 1){//如果到达最后一个,返回true return true; } b[i][j]=true; if(i > 0 && !b[i-1][j] && search(board,i-1,j,b,index+1,w)){//如果i>0,且i-1的值没有被使用,搜索 return true; } if(i<(board.length-1)&&!b[i+1][j]&&search(board,i+1,j,b,index+1,w)){ return true; } if(j>0&&!b[i][j-1]&&search(board,i,j-1,b,index+1,w)){ return true; } if(j<(board[0].length-1)&&!b[i][j+1]&&search(board,i,j+1,b,index+1,w)){ return true; } b[i][j]=false; return false; } }
0 0
- Medium 79题 Word Search
- 79、 Word Search (Medium)
- [Leetcode 79, Medium] Word Search
- LeetCode-79-Word Search(回溯法)-Medium
- Leetcode OJ 79 Word Search [Medium]
- 【Medium】79. Word Search
- 79. Word Search -Medium
- Leetcode 79. Word Search (Medium) (cpp)
- Medium 139题 Word Break
- [Leetcode 211, Medium] Add and Search Word - Data structure design
- LeetCode刷题(C++)——Word Search(Medium)
- Medium 35题 Search Insert Position
- Medium 34题 Search for a Range
- Medium 173题 Binary Search Tree Iterator
- Medium 98题 Validate Binary Search Tree
- Leetcode 79 Word Search
- LeetCode 79: Word Search
- [leetcode 79] Word Search
- wget递归下载文件夹
- 2016/10/01,2016/10/02
- 如何检查IP是否为内网IP
- 动态规划之01背包问题
- Medium 139题 Word Break
- Medium 79题 Word Search
- 协变与逆变
- Medium 80题 Remove Duplicates from Sorted Array II
- 简单C# MVC 通信录,使用REST API 应用到 Azure (有源码)
- Missing Number
- Medium 50题 Pow(x, n)
- 大数据干货贴
- 申请微软Azure(云服务) 免费账号和安装Application Insight(网站健康监控)
- 一个REST API 在Azure上应用的简单通讯录例子。(C#, MVC)