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

    package algorithms;
    
    import java.util.Arrays;
    
    public class Exp3_2 {
        private int pathLength;
        private int rows;
        private int cols;
        private boolean[][] visited;
        char[] wordArray;
    
        public boolean exist(char[][] board, String word) {
            if (board == null)
                return false;
    
            rows = board.length;
            cols = board[0].length;
            // 记录该元素是否已经被访问过了
            visited = new boolean[rows][cols];
            for(int i=0;i<rows;i++)
                Arrays.fill(visited[i], false);
            wordArray = word.toCharArray();
            pathLength = 0;
    
            for (int i = 0; i < rows; i++)
                for (int j = 0; j < cols; j++) {
                    if (findPath(board, i, j)) {
                        return true;
                    }
                }
            return false;
        }
    
        private boolean findPath(char[][] board, int i, int j) {
            boolean flag = false;
            if (pathLength == wordArray.length)
                return true;
            if (i >= 0 && i < rows && j >= 0 && j < cols && board[i][j] == wordArray[pathLength]
                    && visited[i][j] == false) {
                pathLength++;
                visited[i][j] = true;
                flag = findPath(board, i+1, j) || findPath(board, i-1, j) || findPath(board, i, j+1)
                        || findPath(board, i, j-1);
                if (!flag) {
                    pathLength--;
                    visited[i][j] = false;
                }
            }
            return flag;
        }
        
        public static void main(String[] args) {
            char[][] board= {{'a','b','c','e'},{'s','f','c','s'},{'a','d','e','e'}};
            String word = "abcced";
            boolean b = new Exp3_2().exist(board, word);
            System.out.println(b);
        }
    }
  • 相关阅读:
    IDEA 工具使用报错总结
    Struts2 值栈总结(ValueStack)
    hibernate 中映射关系配置
    Java 注解之总结
    ssh_整合总结
    Ajax 请求之_请求类型详解
    C++的重载赋值运算符
    vector容器使用reserve预留空间
    C++中的内存分配
    C++ const修饰指针
  • 原文地址:https://www.cnblogs.com/ustc-anmin/p/10690008.html
Copyright © 2011-2022 走看看