[Leetcode] Word Search

来源:互联网 发布:淘宝开店客服的子账号 编辑:程序博客网 时间:2024/05/16 17:26

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 =

[  ['A','B','C','E'],  ['S','F','C','S'],  ['A','D','E','E']]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,

word = "ABCB", -> returns false.

public class Solution {    public boolean exist(char[][] board, String word) {        int row = board.length;        int column = board[0].length;        boolean[][] record = new boolean[row][column];        for(int i = 0; i < row; i++) {            for(int j = 0; j < column; j++) {                if(exist(word, board, record, i, j)){                    return true;                }            }        }        return false;    }        private boolean exist(String word, char[][] board, boolean[][] record, int x, int y) {        if(word.equals("")) {            return true;        }        if(x < 0 || x >= record.length || y < 0 || y >= record[0].length) {            return false;        }        if(record[x][y]) {            return false;        }        if(board[x][y] != word.charAt(0)) {            return false;        }                String subString = word.substring(1);        record[x][y] = true;        if(exist(subString, board, record, x - 1, y) || exist(subString, board, record, x + 1, y) ||        exist(subString, board, record, x, y - 1) || exist(subString, board, record, x, y + 1)) {            return true;        }        record[x][y] = false;        return false;    }}


0 0