zoukankan      html  css  js  c++  java
  • Word Search, 在矩阵中寻找字符串,回溯算法

    问题描述:

    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.

    算法分析:回溯算法问题。遍历字母表矩阵,然后判断每个字母的上下左右方向是否匹配。维护一个visited数组,来记录路径上已经访问过的元素,防止重复访问。

    public class WordSearch
    {
    	    private int row;
    		private int col;
    	    public boolean exist(char[][] board, String word) {
    			row = board.length;
    			col = board[0].length;
    			boolean[][] visited = new boolean[row][col];
    			for (int i = 0; i < row; i++) 
    			{
    				for (int j = 0; j < col; j++) 
    				{
    					if (dfs(board, word, 0, i, j, visited))
    						return true;
    				}
    			}
    			return false;
    		}
    
    		private boolean dfs(char[][] board, String word, int index, int rowindex,
    				int colindex, boolean[][] visited) 
    		{
    			if (index == word.length())//word全部匹配,直接返回true
    				return true;
    			if (rowindex < 0 || colindex < 0 || rowindex >= row || colindex >= col)
    				return false;
    			if (visited[rowindex][colindex])//路径上一步访问过,就忽略
    				return false;
    			if (board[rowindex][colindex] != word.charAt(index))//不匹配,直接返回false
    				return false;
    			visited[rowindex][colindex] = true;//匹配,置visited为true
    			//当前元素的上下左右是否匹配,只要有一个方向匹配,返回true
    			boolean res = dfs(board, word, index + 1, rowindex - 1, colindex,
    					visited)
    					|| dfs(board, word, index + 1, rowindex + 1, colindex, visited)
    					|| dfs(board, word, index + 1, rowindex, colindex + 1, visited)
    					|| dfs(board, word, index + 1, rowindex, colindex - 1, visited);
    			visited[rowindex][colindex] = false;//递归完后将visited重置为false
    			return res;
    		}
    }
    
  • 相关阅读:
    To do list
    2020 上半学期比赛记录
    板子
    Project Euler 1~10 野蛮题解
    卡常火车头
    防止unordered_map 被卡方法
    2019 香港区域赛 BDEG 题解
    2019徐州区域赛 ACEFM 题解 & pollard-rho & miller-rabin & 求出每个子树的重心 板子
    BST-splay板子
    ZJOI2017(2) 游记
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5796714.html
Copyright © 2011-2022 走看看