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;
}
}