79. Word Search
来源:互联网 发布:淘宝卖lol限定皮肤 编辑:程序博客网 时间:2024/06/04 19:40
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求解,程序如下所示:
class Solution { public boolean dfs(char[][] board, boolean[][] isVisited, int len, String word, int i, int row, int j, int col){ if (len==word.length()){ return true; } if (i < 0||j < 0||i >= row || j >= col){ return false; } if (board[i][j] != word.charAt(len)){ return false; } if (isVisited[i][j] == false) { isVisited[i][j] = true; if(dfs(board, isVisited, len+1, word, i + 1, row, j, col)|| dfs(board, isVisited, len+1, word, i - 1, row, j, col)|| dfs(board, isVisited, len+1, word, i, row, j + 1, col)|| dfs(board, isVisited, len+1, word, i, row, j - 1, col)){ return true; } isVisited[i][j] = false; } return false; } public boolean exist(char[][] board, String word) { if (board.length == 0){ return false; } int row = board.length, col = board[0].length; for (int i = 0; i < row; ++ i){ for (int j = 0; j < col; ++ j){ if (board[i][j] == word.charAt(0)){ boolean[][] isVisited = new boolean[row][col]; if (dfs(board, isVisited, 0, word, i, row, j, col)){ return true; } } } } return false; }}
阅读全文
0 0
- LeetCode 79. Word Search
- [LeetCode]79.Word Search
- LeetCode --- 79. Word Search
- [Leetcode] 79. Word Search
- 79. Word Search
- [leetcode] 79.Word Search
- 【leetcode】79. Word Search
- 79. Word Search
- 79. Word Search
- [LeetCode]79. Word Search
- 79. Word Search LeetCode
- 79. Word Search
- 79. Word Search
- 79. Word Search
- leetcode 79. Word Search
- LeetCode 79. Word Search
- LeetCode 79. Word Search
- leetcode 79. Word Search
- 个人理解(非)阻塞与同步异步
- shell学习之十八--nginx启动脚本(if)
- vuex
- 数据结构|专业学习思维
- java读取properties配置文件的几种方式
- 79. Word Search
- 基于SQLite的安卓平台用户信息管理系统
- SpringMvc之值(View到Controller)的传递-yellowcong
- Unity3D更改游戏鼠标样式
- 数据库建表方法
- 【Python编程:从入门到实践】第十章:文件和异常
- PAT (Basic Level) Practise (中文)1055. 集体照 (25)
- 一个看似简单的数字交换问题
- POJ1912_A highway and the seven dwarfs_判断凸包与直线是否相交