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;
        }
    }
  • 相关阅读:
    Python元类
    Python接口与归一化设计
    如何使用yum下载rpm包
    浅谈Python的with语句
    搞懂了这几点,你就学会了Web编程
    网络虚拟化技术大观
    Python装饰器
    Kubernetes配置Ceph RBD StorageClass
    编译Kubelet二进制文件
    记一次虚拟机无法挂载volume的怪异问题排查
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3753370.html
Copyright © 2011-2022 走看看