leetcode_Word Search
来源:互联网 发布:淘宝怎么避免同款 编辑:程序博客网 时间:2024/06/08 17:24
题目描述:
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.
——————————————————————————————
由于每个数只能访问不超过一次,就想找一条只能横或者竖的线段,自然而然想到用DFS。
1.DFS要注意如何标记已访问的和未访问的,用“#”赋值已访问的,若发现已经不可行了,将原来的数还原。
2.每次可访问的是 上下左右未越界且未访问。
public class Solution3 { public boolean exist(char[][] board, String word) { for(int i=0;i<board.length;i++){ for(int j=0;j<board[i].length;j++){ if(exist(board,i,j,word,0))return true; } } return false; } public boolean exist(char[][] board,int x,int y,String word,int index){ if(index>=word.length()) return true; if(x<0||x>=board.length||y<0||y>=board[0].length)return false; if(board[x][y]==word.charAt(index)){ index++; char c=board[x][y]; board[x][y]='#'; boolean tmp=(exist(board, x-1,y,word,index)||exist(board, x+1, y, word, index)|| exist(board, x, y-1, word, index)||exist(board, x, y+1, word, index)); board[x][y]=c; return tmp; } return false; } public static void main(String[] args){ char[][] board={{'a','a'}}; String word="aaa"; System.out.println(new Solution3().exist(board, word)); }}
(自己的代码实在冗余了,以上代码参考过leetcode discussion simple solution)
0 0
- LeetCode_Word Search
- leetcode_Word Search
- Leetcode_word-search(c++ version)
- LeetCode_Word Ladder
- LeetCode_Word Break
- LeetCode_Word Ladder
- leetcode_Word Break
- leetcode_Word Pattern
- leetcode_Word Pattern
- leetCode_Word Break
- leetCode_Word BreakII
- Leetcode_word-break-ii
- Leetcode_word-ladder(c++ version)
- Leetcode_word-ladder-ii
- LeetCode_Word Break II
- 【题解】leetcode_Word Frequency
- leetCode_Word Ladder【BFS】
- Leetcode_word-break(c++ and python version)
- 悲哀的 ASI ,ASI 与 AFN 的区别
- 动态规划法之蜘蛛侠救美记
- 看看最新的考试 c语言 noip模拟 纯llq原创作品
- KMP算法
- 动态规划学习之三种方法解决斐波拉契数
- leetcode_Word Search
- static关键字用法
- PHP中用到的一些正则
- 爬虫--scrapy 初探
- 解读HTTP包
- Extjs 上传文件 IE不兼容的问题[提示下载保存]
- 数据库事务四大特性
- C语言中||\这个符号\是连接符,不是换行,
- 排序算法---希尔排序