zoukankan      html  css  js  c++  java
  • 79. Word Search java solutions

    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.

    Subscribe to see which companies asked 

     1 public class Solution {
     2     public boolean exist(char[][] board, String word) {
     3         if(word == null || word.length() == 0) return true;
     4         boolean[][] visit = new boolean[board.length][board[0].length];
     5         char[] words = word.toCharArray();
     6         for(int i = 0; i < board.length; i++){
     7             for(int j = 0; j < board[0].length; j++){
     8                 if(BFS(board,visit,words,0,i,j)) return true;
     9             }
    10         }
    11         return false;
    12     }
    13     
    14     public boolean BFS(char[][] board,boolean[][] visit, char[] word, int len, int row, int col){
    15         if(len == word.length){
    16             return true;
    17         }
    18         if(row < 0 || row == board.length || col < 0 || col == board[row].length) return false;
    19         if(board[row][col] != word[len]) return false;
    20         if(!visit[row][col]){
    21         visit[row][col] = true;
    22         boolean tmp = BFS(board,visit,word,len+1,row,col+1) ||
    23                 BFS(board,visit,word,len+1,row,col-1) || BFS(board,visit,word,len+1,row+1,col) ||
    24                 BFS(board,visit,word,len+1,row-1,col);
    25         visit[row][col] = false;
    26         return tmp;
    27         }else return false;
    28     }
    29 }

    BFS 方法的代码逻辑等二刷时候再修改学习下。

  • 相关阅读:
    自动化生成测试报告
    测试用例设计的常见几种方法
    python的七种数据类型
    python读写文件的几种方法
    测试工具之fiddler
    自动化前置用例和后置用例
    python的几种数据类型以及举例
    Selenium请求库
    第一篇帖子,上火了
    汉诺塔算法
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5650727.html
Copyright © 2011-2022 走看看