zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    状态码
    vue+element下拉选项添加点击事件可跳转或触发事件
    position定位
    vue+element下拉菜单添加事件
    vue封装接口
    vue+element实现导入excel并拿到返回值
    10. EIGRP的stud
    9. EIGRP认证和默认路由
    8. EIGRP负载均衡
    7. EIGRP中应用偏移列表
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4349936.html
Copyright © 2011-2022 走看看