zoukankan      html  css  js  c++  java
  • 【WordSearch】Word Search

    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.

    public class Solution {
        public boolean exist(char[][] board, String word) {
            if(word.length()==0)
                return true;
            if(board.length==0)
                return false;
            boolean[][] bol = new boolean[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)&&findExist(i,j,0,board,bol,word)){
                        return true;
                    }
                }
            }
            return false;
            
        }
    
        private boolean findExist(int x, int y,int wa, char[][] board, boolean[][] bol, String word) {
            if(wa>=word.length())
                return true;
            if(x<0||y<0)
                return false;
            if(x>=board.length||y>=board[x].length)
                return false;
            if(bol[x][y])
                return false;
            if(board[x][y]!=word.charAt(wa))
                return false;
                        
                bol[x][y]=true;
                boolean re =findExist(x+1,y,wa+1,board,bol,word)||findExist(x,y+1,wa+1,board,bol,word)||
                        findExist(x-1,y,wa+1,board,bol,word)||findExist(x,y-1,wa+1,board,bol,word);
                bol[x][y]=false;
            return re;
        }
    }
  • 相关阅读:
    VUE 源码工具
    elasticsearch 根据主键_id更新部分字段
    Linux下解压文件到其他目录
    centos 7 安装docker
    英语阅读
    将Word文件上传到博客园
    kafka
    ubantu批量下载依赖包+apt命令list
    llvm.20.SwiftCompiler.Compiler-Driver
    Java获取resources文件夹下properties配置文件
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3753370.html
Copyright © 2011-2022 走看看