• 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 }
  • 相关阅读:
    jfinal的configPlugin基本配置代码
    jfinal的maven配置
    access denied XXXXXXXXXXXX
    常见排序算法小结
    String、StringBuffer与StringBuilder之间区别
    进程间的通信方式
    从右上角到左下角沿反对角线打印方阵中的元素
    快乐数问题
    数组循环移位问题
    HTTP协议报文格式
  • 原文地址:https://www.cnblogs.com/jasonC/p/3429877.html
Copyright © 2020-2023  润新知