• 【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;
        }
    }
  • 相关阅读:
    备忘录模式---行为型
    观察者模式(Observer)---行为型
    Hadoop基础
    centos执行-查看,复制,删除-命令的脚本
    权限问题
    12月centos单词
    配置集群遇到的问题
    SSH--完全分布式主机设置【克隆过安装过Hadoop的主机后】
    java随机排座位
    NewWord
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3753370.html
Copyright © 2020-2023  润新知