Leetcode 79 单词搜索 解题报告

1 解题思想

一个二维矩阵,每个位置放入一个单词。
给定一个单词,试问是否能够在这个矩阵中找到一条线(仅允许上下左右联通,不能交叉)正好能按顺序标示这个单词?

这道题我的做法比较暴力,直接搜索了,没什么太多好说的。

2 原题

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.

3 AC解

public class Solution {
    static int[] dx={0,1,0,-1};
    static int[] dy={1,0,-1,0};
    public boolean find(char[][] board,char[] words,boolean flag[][],int i,int j,int index){
        //System.out.println(i+" "+j+" "+words[index]);
        if(words.length==index)
            return true;
        for(int k=0;k<4;k++){
            int di=i+dx[k];
            int dj=j+dy[k];
            if(di>=0 && di<board.length && dj>=0 && dj<board[0].length && flag[di][dj]==false && words[index]==board[di][dj]){
                flag[di][dj]=true;
                if(find(board,words,flag,di,dj,index+1)) return true;
                flag[di][dj]=false;
            }
        }
        return false;
    }
    public boolean exist(char[][] board, String word) {
        int n=board.length,m=board[0].length;
        boolean flag[][]=new boolean[n][m];
        char[] words=word.toCharArray();
        System.out.println(n+" "+m);
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++){
                flag[i][j]=true;
                if(board[i][j]==words[0] && find(board,words,flag,i,j,1))
                    return true;
                flag[i][j]=false;
            }
        return false;
    }
}

你可能感兴趣的:(LeetCode,搜索)