LeetCode 79. Word Search

来源:互联网 发布:qq空间 for mac客户端 编辑:程序博客网 时间:2024/06/03 17:52

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) {        if(word.length()==0)return true;        if(board.length==0||board[0].length==0)return false;        boolean used[][] = new boolean[board.length][board[0].length];        for(int i=0;i<board.length;i++){            for(int j=0;j<board[0].length;j++){                if(helper(board,i,j,0,used,word))return true;            }        }        return false;    }    public boolean helper(char[][]board,int i,int j,int n,boolean[][]used,String word){        if(n==word.length())return true;        if(i<0||j<0||i>=board.length||j>=board[0].length||used[i][j]||board[i][j]!=word.charAt(n))return false;        used[i][j] = true;        boolean res = (helper(board,i+1,j,n+1,used,word)||helper(board,i-1,j,n+1,used,word)||               helper(board,i,j-1,n+1,used,word)||helper(board,i,j+1,n+1,used,word));        used[i][j] = false;        return res;    }}



原创粉丝点击