LeetCode006:WordSerarch

23 篇文章 0 订阅
8 篇文章 0 订阅
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值