LeetCode OJ算法题(七十九):Word Search

题目:

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.

For example,
Given board =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word  =  "ABCCED" , -> returns  true ,
word  =  "SEE" , -> returns  true ,
word  =  "ABCB" , -> returns  false .

解法:

题目要求在一个二维表中查找单词,按邻居顺序排列即可。

这里很容易想到利用深度优先遍历的思想,找到一个元素与word[i]匹配后,按上下左右的顺序检查它的邻居是否与word[i+1]匹配。当i>=word.length时,即宣告查找成功。

需要注意的是每个元素只能访问一遍,因此可以用一个visit二维数组来存储对应元素是否被访问过,也可以用一个变量保存当前访问的元素,然后将其置为‘。’,表示它已被访问,在DFS结束后恢复现场。

这题对时间卡的非常紧,所以尽量避免一些不太需要的比较,才能AC。

public class No79_WordSearch {
	public static void main(String[] args){
		System.out.println(exist(new char[][]{{'B'},{'A'},{'B'}}, "BABA"));
	}
	public static boolean exist(char[][] board, String word) {
        int m = board.length;
        if(m == 0) return false;
        int n = board[0].length;
        if(n == 0) return false;
        for(int i=0;i<m;i++){
        	for(int j=0;j<n;j++){
        		if(match(board, word, 0, i, j)) return true;
        	}
        }
        return false;
    }
	public static boolean match(char[][] board, String word, int index, int i, int j){
		if(index >= word.length()) return true;
		if(i<0 || i>=board.length || j<0 || j>=board[0].length) return false;
		if(word.charAt(index) != board[i][j]) return false;
		if(board[i][j] == '.') return false;
		char tmp = board[i][j];
		board[i][j] = '.';
		boolean top = false, bottom = false, left = false, right = false;
		if(i>=1)
			top = match(board, word, index+1, i-1, j);
		if(!top)
			bottom = match(board, word, index+1, i+1, j);
		if(!top && !bottom)
			left = match(board, word, index+1, i, j-1);
		if(!top && !bottom && !left)
			right = match(board, word, index+1, i, j+1);
		board[i][j] = tmp;
		return top||bottom||left||right;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值