zoukankan      html  css  js  c++  java
  • LeetCode--word search

    package leetcode;

    public class WordSearch2 {

        public static int[] DX = { 0, 1, 0, -1 };
        public static int[] DY = { 1, 0, -1, 0 };

        public static boolean exist(char[][] board, String word) {
            int m = board.length;
            int n = board[0].length;
            boolean[][] visited = new boolean[m][n]; // 初始都为0,都未读状态

            for (int i = 0; i != m; i++) {
                for (int j = 0; j != n; j++) {
                    if (board[i][j] == word.charAt(0)) {
                        if (word.length() == 1) {
                            return true;
                        }
                        visited[i][j] = true;
                        if (Vertify(board, visited, 0, i, j, word))
                            return true;
                    }
                }
            }
            return false;
        }

        public static boolean Vertify(char[][] board, boolean[][] visited, int k, int x, int y, String word) {
            for (int a = 0; a != 4; a++) {
                int xx = x + DX[a];
                int yy = y + DY[a];
                if (xx < board.length && yy < board[0].length && yy >= 0 && xx >= 0) {
                    if (visited[xx][yy] == true)
                        continue;
                    if (board[xx][yy] == word.charAt(k)) {
                        visited[xx][yy] = true;
                        if (k == word.length()-1) // 难点:怎么去记录这个点是否走过,怎么用计数器记录操作过的字符?
                            return true;
                        else
                            Vertify(board, visited, k + 1, xx, yy, word); // 不用很了解回溯的过程!
                    } else {
                        visited[xx][yy] = false; // if/for等语句,找好其范围是关键,不要改程序的时候,将if管的范围给弄混乱!否则出现数组越界等等问题
                                                    // 改“{” 想到 “}”
                    }
                }
            }

            return false;

        }

        public static void main(String[] args) {
            // TODO Auto-generated method stub
             char[][] board = {{'C','A','A'},{'A','A','A'},{'B','C','D'}};  
                String word = "AAB";  
                System.out.println(exist(board, word));  
        }

    }

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    Html.Partial和Html.RenderPartial, Html.Action和Html.RenderAction的区别
    cygwin下git出现cabundle.crt相关错误的解决办法
    Orchard CMS前台页面为什么没有Edit链接?
    Entity Framework练习题
    分析Autofac如何实现Controller的Ioc(Inversion of Control)
    在Winform,Silvelight,WPF等程序中访问Asp.net MVC web api
    适合.net程序员的.gitignore文件
    如何处理Entity Framework中的DbUpdateConcurrencyException异常
    Asp.net MVC中repository和service的区别
    smplayer中使用srt字幕乱码问题
  • 原文地址:https://www.cnblogs.com/neversayno/p/5213542.html
Copyright © 2011-2022 走看看