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
原创粉丝点击