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;
        }
    }
  • 相关阅读:
    Objective-C基础3
    C语言回顾-结构体、枚举和文件
    C语言回顾-内存管理和指针函数
    C语言回顾-字符串指针
    C语言回顾-指针
    C语言回顾-二维数组
    Objective-C基础2
    C语言回顾-整型变量修饰符和一维数组
    sql server 判断是否存在数据库,表,列,视图
    大文件数据库脚本导入解决方案
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3753370.html
Copyright © 2011-2022 走看看