leetcode 79. Word Search

33 篇文章 0 订阅
30 篇文章 0 订阅

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.

Example:

board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]

Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.

tag : array, backtracking

method 1

使用一个访问辅助数组,在每次访问时置为true,如果这次访问没有得到完整的目标word,就再把辅助访问数组对应的值置为false

boolean[][] visit;

public boolean exist(char[][] board, String word) {
    visit = new boolean[board.length][board[0].length];

    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[i].length; j++) {
            if (board[i][j] == word.charAt(0)) {
                if (exist2(board, word, 0, i, j))
                    return true;
            }
        }
    }
    return false;
}

private boolean exist(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[i].length || visit[i][j] || board[i][j] != word.charAt(index) || visit[i][j])
        return false;

    visit[i][j] = true;
    if (exist(board, word, index + 1, i + 1, j) || exist(board, word, index + 1, i, j + 1) || exist(board, word, index + 1, i - 1, j) || exist(board, word, index + 1, i, j - 1))
        return true;

    visit[i][j] = false;
    return false;
}

method 2

可以对method 1 进行优化,使得空间复杂度变为O(1)

即在访问时,将该位置的字符置为其他不存在干扰的字符,当访问结束没有得到完整的目标word时,再置回,运用了位操作

private boolean exist2(char[][] board, String word, int index, int y, int x) {
    if (index == word.length()) return true;
    if (y < 0 || x < 0 || y == board.length || x == board[y].length) return false;
    if (board[y][x] != word.charAt(index)) return false;
    board[y][x] ^= 256;
    boolean exist = exist(board, word, index + 1, y, x + 1)
            || exist(board, word, index + 1, y, x - 1)
            || exist(board, word,index+1,y + 1, x)
            || exist(board, word,index+1,y - 1, x);
    board[y][x] ^= 256;
    return exist;
}

summary:

  1. 需要记录访问呢轨迹时,使用一个访问数组,并且在这个分支回溯完成后,把访问数组中该位置置回原来的值
  2. 也可以不用访问数组,那么就必须标记这个位置的数已经被访问过,可以
    1. 使用其他根本不会干扰的字符,结束之后再置回原来的数,使用位操作^256
    2. 在不会再被访问的位置标记该数(见73)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值