zoukankan      html  css  js  c++  java
  • Word Search

    DFS

     1 public class Solution {
     2     public boolean exist(char[][] board, String word) {
     3         if(word == null || word.length() < 1)
     4             return false;
     5         HashSet<Integer> done = new HashSet<Integer>();
     6         
     7         for(int i = 0; i < board.length; i++)
     8             for(int j =0; j < board[0].length; j++){
     9                 if(generate(board, i, j, 0, word, done))
    10                     return true;
    11             }
    12         
    13         return false;
    14     }
    15     
    16     private boolean generate(char[][] board, int row, int column, int depth, String word, HashSet<Integer> done){
    17         if(row < 0 || column < 0 || row >= board.length || column >= board[0].length)
    18             return false;
    19         int loc = row * board[0].length + column;
    20         if(done.contains(loc))
    21             return false;
    22         if(board[row][column] == word.charAt(depth)){
    23             if(depth == word.length()-1)
    24                 return true;
    25             done.add(loc);
    26             if(generate(board, row+1, column, depth+1,word,done))
    27                 return true;
    28             if(generate(board, row, column+1, depth+1,word,done))
    29                 return true;
    30             if(generate(board, row-1, column, depth+1,word,done))
    31                 return true;
    32             if(generate(board, row, column-1, depth+1,word,done))
    33                 return true;
    34             done.remove(loc);
    35         }
    36         return false;
    37     }
    38 }
  • 相关阅读:
    字符串题目
    Java 练习题摘录
    数据库原理及应用-引言
    数学类题目
    牛顿法
    动态规划-最大子段和
    判断数幂
    杭电1096
    算法导论01 几种排序以及其时间复杂度01
    杭电2059龟兔赛跑
  • 原文地址:https://www.cnblogs.com/jasonC/p/3429877.html
Copyright © 2011-2022 走看看