LeetCode Word Search
来源:互联网 发布:手机荧光灯软件 编辑:程序博客网 时间:2024/06/13 00:07
Description:
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.
Solution:
一开始题目理解有误,没想到是DFS。不过LeetCode一直被人诟病的问题就是没有数据范围了。也导致了我想复杂了,以为是字符串题目了……囧
不过既然DFS可以解决的话,那么基本就是最普通的解决方案了,因为只是上下左右移动,实际上比经典问题“骑士周游”简单很多,虽说二者本质一样,大家感兴趣可以做做。
import java.util.*;public class Solution {int[][] direction = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };boolean[][] vis;int n, m;String word;char[][] board;public boolean exist(char[][] board, String word) {this.board = board;this.word = word;m = board.length;n = board[0].length;vis = new boolean[m][n];for (int i = 0; i < m; i++)Arrays.fill(vis[i], false);for (int i = 0; i < m; i++)for (int j = 0; j < n; j++)if (dfs(i, j, 0))return true;return false;}boolean dfs(int i, int j, int index) {// 当前的index必须和word matchif (word.charAt(index) != board[i][j])return false;// 不可以实现走过if (vis[i][j])return false;if (index + 1 == word.length())return true;vis[i][j] = true;int ti, tj;for (int d = 0; d < 4; d++) {ti = i + direction[d][0];tj = j + direction[d][1];if (valid(ti, tj) && dfs(ti, tj, index + 1))return true;}vis[i][j] = false;return false;}boolean valid(int i, int j) {if (i >= 0 && i < m && j >= 0 && j < n)return true;return false;}}
0 0
- LeetCode: Word Search
- [Leetcode] Word Search
- LeetCode : Word Search
- Leetcode: Word Search
- [LeetCode] Word Search
- leetcode 56: Word Search
- Leetcode 79 Word Search
- [leetcode ] word search
- [Leetcode] Word Search
- [LeetCode]Word Search
- Leetcode Word Search
- [leetcode]word search
- [leetcode] Word Search
- LeetCode-Word Search
- [LeetCode] Word Search
- LeetCode - Word Search
- leetcode word search
- LeetCode:Word Search
- 封装顶部选择按钮(用block实现在当前控制器下面添加button点击方法)
- Tween算法及缓动效果
- html学习笔记
- leetcode 总结,记录,备忘。153
- 大厅的列表服务预览
- LeetCode Word Search
- OCSP server in Windows2012R2 详细搭建过程
- 最常用的字
- oracle 2
- DWZ(三):常用组件了解
- 在命令行状态下,如何运行编译后的.class 文件???
- Python学习十四:filter()
- Mission系统预览
- python编程之键盘响应