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);
        }
    }
  • 相关阅读:
    C++友元
    C++类与static
    C++const
    reinterpret_cast应用
    学习软件工程课的心得上
    学习软件工程课的心得下
    项目总结报告之假如历史重新再来一次
    人月神话读后感
    团队任务考核
    冲刺周期会议十一
  • 原文地址:https://www.cnblogs.com/ustc-anmin/p/10690008.html
Copyright © 2011-2022 走看看