leetcode: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", -> return true,
word ="SEE", -> return true,
word ="ABCB", -> return false.

解题思路:

  1. 这题是典型的 DFS 问题,同样需要运用到递归
  2. 设置一个 visited 数组,用来记录节点是否被访问过
  3. 从二维数组 0,0 开始递归,如果 word 与 board 相符,则递归调用当前元素上下左右的四个位置,直至 word 长度被返回

代码如下:

    // 记录元素是否被访问过
    boolean [][] visited = null;
    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        visited = new boolean [m][n];

        char [] words = word.toCharArray();
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
			
		// 如果返回为真,就返回 true,否则继续遍历下一个字母
                if(search(0,i,j,board,words,visited))
                    return true;
            }
        }
        return false;
    }

    // 递归函数,
    public boolean search(int index,int i, int j,char [][] board, char [] words,boolean [][] visited ){
       // 如果 index 的长度等于 word 的长度,就返回 true
  	if(index == words.length) return true;
        int m = board.length;
        int n = board[0].length;

	// 这里需要全面的判断 i, j,因为 i,j 在后面会执行 +1, -1 的操作 
        if(i < 0 || j < 0 || i >= m || j >= n
                || visited[i][j] || board[i][j] != words[index])
            return false;

	// 将当前的元素设置为已访问
        visited[i][j] = true;
	
	// 递归处理该元素的上下左右四个节点
        boolean re = search(index + 1,i - 1,j,board,words,visited)
                    || search(index + 1,i + 1,j,board,words,visited)
                    || search(index + 1,i,j - 1,board,words,visited)
                    || search(index + 1,i,j + 1,board,words,visited);
        
	// 递归结束,恢复该元素的状态
	visited[i][j] = false;
        return re;
    }

转载于:https://my.oschina.net/happywe/blog/3071269

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值