LeetCode006:WordSerarch
来源:互联网 发布:支持的承载网络 编辑:程序博客网 时间:2024/06/11 00:33
package com.abuge;/** * 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. * 题意:给定一个二维字符数组,从中进行深度优先搜索判断是否存在所求字符串 * @author AbuGe * */public class Solution {private int row;private int col;public boolean exist(char[][] board, String word){row = board.length;col = board[0].length;boolean[][] visited = new boolean[row][col];//访问状态for(int i = 0; i < row; i++){for(int j = 0; j < col; j++){if(dfs(board, i, j, word, 0, visited)){return true;}}}return false;}//深度优先搜索(也就是递归的一种实现方式)public boolean dfs(char[][] board, int rowIndex, int colIndex, String word, int index, boolean[][] visited){//递归出口if(index == word.length())return true;if(rowIndex < 0 || colIndex < 0 || rowIndex >= row || colIndex >= col)return false;if(visited[rowIndex][colIndex])return false;if(board[rowIndex][colIndex] != word.charAt(index))return false;//符合条件的遍历visited[rowIndex][colIndex] = true;//开始递归下一个字符,从当前字符的上下左右四个方向进行遍历boolean result = dfs(board, rowIndex - 1, colIndex, word, index + 1, visited) || dfs(board, rowIndex + 1, colIndex, word, index + 1, visited) || dfs(board, rowIndex, colIndex - 1, word, index + 1, visited) || dfs(board, rowIndex, colIndex + 1, word, index + 1, visited);//将状态恢复至初始状态,以便下次正确的遍历(这一句很重要)visited[rowIndex][colIndex] = false;return result;}}
参考:http://blog.csdn.net/yiding_he/article/details/18893621
0 0
- LeetCode006:WordSerarch
- leetcode006:ZigZag Conversion
- leetcode006 ZigZag Conversion
- Leetcode006-ZigZag Conversion
- LeetCode006 ZigZag Conversion
- leetcode006-Search for a Range
- Leetcode006:ZigZag Conversion的Java解法
- Leetcode006--字符串的Z字型打印
- 【LeetCode006算法/编程练习C++】ZigZag Conversion //折形string重新排序
- LuaXml 简单介绍
- eclipse无法自动编译问题汇总
- 各类 HTTP 返回状态代码详解
- 125个基本的C#面试问答
- 016_计算机体系结构一
- LeetCode006:WordSerarch
- IOS之UILabel显示内容自动换行
- poj1088(dp)
- Android onClick事件三种实现方法
- 粉红哥几天今天放几天假
- 360在网站安全防护中的实践
- 判断二叉树是不是平衡
- const的那些事
- H-1028-Ignatius and the Princess III