• leetcode------Word Search


    标题: Word Search
    通过率: 20.0%
    难度: 中等

    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.

    需要尝试从每一个位置起开始遍历,每次向四个方向开始遍历,如果四个方向都不满足时要将走过的路径回复,边界问题看代码:

    用一个index记录查了多少个了。

    迭代算法依然没有知道突破口:

     1 public class Solution {
     2     private int m,n;
     3     public boolean exist(char[][] board, String word) {
     4         m=board.length;
     5         n=board[0].length;
     6         boolean [][] visted=new boolean[m][n];
     7         for(int i=0;i<m;i++)
     8         for(int j=0;j<n;j++){
     9             if(dfs(board,word,0,i,j,visted))
    10                 return true;
    11         }
    12         return false;
    13     }
    14     public boolean dfs(char[][] board, String word,int index,int startx,int starty,boolean [][] visted){
    15         if(index==word.length())return true;
    16         if(startx<0||startx>=m||starty<0||starty>=n)return false;
    17         if(visted[startx][starty])return false;
    18         if(board[startx][starty]!=word.charAt(index))return false;
    19         visted[startx][starty]=true;
    20         boolean res=dfs(board,word,index+1,startx+1,starty,visted)||dfs(board,word,index+1,startx-1,starty,visted)||dfs(board,word,index+1,startx,starty+1,visted)||dfs(board,word,index+1,startx,starty-1,visted);
    21         visted[startx][starty]=false;
    22         return res;
    23     }
    24 }
  • 相关阅读:
    线程池问题
    高级I/O
    闹钟设计
    线程竞争问题
    线程基本函数
    SpringMvc支持跨域访问
    gitlab qq邮件配置
    gitlab断电
    docker run always
    电子书网
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4349936.html
Copyright © 2020-2023  润新知