zoukankan      html  css  js  c++  java
  • 079 Word Search 单词搜索

    给定一个二维面板和一个单词,找出该单词是否存在于网格中。
    这个词可由顺序相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
    例如,
    给定 二维面板 =
    [
      ['A','B','C','E'],
      ['S','F','C','S'],
      ['A','D','E','E']
    ]
    单词= "ABCCED",-> 返回 true,
    单词 = "SEE", -> 返回 true,
    单词 = "ABCB", -> 返回 false。
    详见:https://leetcode.com/problems/word-search/description/

    Java实现:

    class Solution {
        public boolean exist(char[][] board, String word) {
            int m = board.length;  
            int n = board[0].length;  
            boolean[][] visited = new boolean[m][n];  
            for (int i = 0; i < m; i++) {  
                for (int j = 0; j < n; j++) {  
                    if (dfs(board, word, 0, i, j, visited)) { 
                        return true;  
                    }
                }  
            }  
            return false;  
        }
        
        public boolean dfs(char[][] board, String word, int index, int rowindex, int colindex, boolean[][] visited) { 
            if (index == word.length()){  
                return true;  
            }
            if (rowindex < 0 || colindex < 0 || rowindex >=board.length || colindex >= board[0].length){
                return false;  
            }
            if (visited[rowindex][colindex]){  
                return false;  
            }
            if (board[rowindex][colindex] != word.charAt(index)){  
                return false;  
            }
            visited[rowindex][colindex] = 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;  
            return res;  
        }
    }
    

    参考:https://www.cnblogs.com/springfor/p/3883942.html

  • 相关阅读:
    Fragment中获取Activity的Context (转)
    raw cannot be resolved or is not a field解决办法
    商业分析07_06分布情况分析
    商业分析07_04漏斗分析
    商业分析07_03数据涨跌异动如何处理
    商业分析07_02多维度拆解
    商业分析07_01对比分析
    商业分析07_00概述 数据分析
    商业分析06选择数据工具
    商业分析05如何选取数据指标
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8711617.html
Copyright © 2011-2022 走看看