Leetcode: Word Search

来源:互联网 发布:家用粉碎机知乎 编辑:程序博客网 时间:2024/06/05 18:40

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.

Search for each element in given board and its neighbors to see whether they can consist to the word. Use a new boolean board to represent whether that element is already used. And each time a new search begins, the boolean board should be false for each element. Time complexity O(m^2 * n ^2).

public class Solution {    public boolean exist(char[][] board, String word) {        if (board == null || board.length == 0 || board[0].length == 0) {            return false;        }                if (word == null || word.length() == 0) {            return true;        }                ArrayList<Integer> x = new ArrayList<Integer>();        ArrayList<Integer> y = new ArrayList<Integer>();        for (int i = 0; i < board.length; i++) {            for (int j = 0; j < board[0].length; j++) {                if (board[i][j] == word.charAt(0)) {                    x.add(i);                    y.add(j);                }            }        }                boolean[][] visited = new boolean[board.length][board[0].length];        for (int i = 0; i < x.size(); i++) {            if (helperExist(board, x.get(i), y.get(i), word, 0, visited)) {                return true;            }        }                return false;    }        private boolean helperExist(char[][] board, int x, int y, String word, int pos, boolean[][] visited) {        if (pos == word.length()) {            return true;        }                if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || visited[x][y] == true || board[x][y] != word.charAt(pos)) {            return false;        }                visited[x][y] = true;        boolean res =  helperExist(board, x - 1, y, word, pos + 1, visited) ||                        helperExist(board, x + 1, y, word, pos + 1, visited) ||                       helperExist(board, x, y - 1, word, pos + 1, visited) ||                       helperExist(board, x, y + 1, word, pos + 1, visited);        visited[x][y] = false;        return res;            }}



0 0