[LeetCode]Word Search

题目:Word Search

判断某一单词是否在一个字母数组中用一条折线连起来。

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED", -> returns true,

坐标序列如下:00,01,02,12,22,21

思路:

递归查找单词当前字母对应数组的坐标的前后左右,看能都匹配。

package com.example.medium;

/**
 * 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.
 * @author FuPing
 *
 */
public class Exist {
    /**
        *@param i,j        当前元素的坐标
        *@param word    查找单词
        *@param k            查找单词的字母的下标
        *@param visit 所有已访问过元素的标记
        */
    private boolean check(char[][] board,int i,int j,String word,int k,int[][] visit){
        if(k >= word.length())return true;
        if(i > 0 && board[i-1][j] == word.charAt(k) && visit[i-1][j] == 0){//查找当前字母的上边
            visit[i-1][j] = 1;
            if(check(board,i-1,j,word,k+1,visit))return true;
            visit[i-1][j] = 0;
        }
        if(j < board[0].length - 1 && board[i][j+1] == word.charAt(k) && visit[i][j+1] == 0){//查找当前字母的右边
            visit[i][j+1] = 1;
            if(check(board,i,j+1,word,k+1,visit))return true;
            visit[i][j+1] = 0;
        }
        if(i < board.length - 1 && board[i+1][j] == word.charAt(k) && visit[i+1][j] == 0){//查找当前字母的下边
            visit[i+1][j] = 1;
            if(check(board,i+1,j,word,k+1,visit))return true;
            visit[i+1][j] = 0;
        }
        if(j > 0 && board[i][j-1] == word.charAt(k) && visit[i][j-1] == 0){//查找当前字母的左边
            visit[i][j-1] = 1;
            if(check(board,i,j-1,word,k+1,visit))return true;
            visit[i][j-1] = 0;
        }
        return false;
    }
    public boolean exist(char[][] board, String word) {
        int[][] visit = new int[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)){//找到与首字母相同的地方
                    visit[i][j] = 1;
                    if(check(board, i, j, word, 1, visit))return true;
                    visit[i][j] = 0;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        char[][] board = {{'a','a','a','a'},
                {'a','a','a','a'},
                {'a','a','a','a'},
                {'a','a','a','a'}};
        System.out.println(new Exist().exist(board, "aaaaaaaaaaaaaaaaaaa"));

    }

}
原文地址:https://www.cnblogs.com/yeqluofwupheng/p/6685493.html