给定一个二维数组和一个单词,找出该单词是否存在于网格中。该单词可以由顺序相邻单元的字母构成,其中“相邻”单元是那些水平或垂直相邻的单元。同一字母单元格不能使用多次。

public class WordSearch
{
private boolean[][] isMarked;
private int[][] dirction= {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
private int row;
private int col;
private String word;
private char[][] board;

public WordSearch(){}

public boolean exist(char[][] board, String word) 
{
	if(board.length==0 || board[0].length==0 || word.length()==0)
    {return false;}
	
	this.row= board.length;this.col= board[0].length;
	this.word= word;this.board= board;
	isMarked= new boolean[row][col];
	
	for(int i=0;i<row;i++)
	{
		for(int j=0;j<col;j++)
		{
			if(DFS(i, j, 0)) {return true;}
		}
	}
	return false;
}

private boolean DFS(int x, int y, int start)
{
	if(start == word.length()-1)
	{return (board[x][y] == word.charAt(start));}
	
	if(board[x][y] == word.charAt(start))
	{
		isMarked[x][y]= true;
		for(int i=0;i<4;i++)
		{
			int temp_x = x + dirction[i][0];
			int temp_y = y + dirction[i][1];
			if(inRange(temp_x, temp_y) && !isMarked[temp_x][temp_y])
			{
				if(DFS(temp_x, temp_y, start+1)) {return true;}
			}
		}
		isMarked[x][y]= false;
	}
	return false;
}

private boolean inRange(int x, int y)
{
	if(x > -1 && x < row && y > -1 && y < col)
	{return true;}
	return false;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值