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));  
        }

    }

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    使用golang访问kubebernetes
    使用 Rancher 管理现有 Kubernetes 集群
    Running powershell scripts during nuget package installation and removal
    How to Create, Use, and Debug .NET application Crash Dumps in 2019
    寻找写代码感觉(一)之使用 Spring Boot 快速搭建项目
    Selenium+Java之解决org.openqa.selenium.InvalidArgumentException: invalid argument报错问题
    Selenium环境搭建
    关于Xpath定位方法知道这些基本够用
    Web自动化之浏览器启动
    【翻译】编写代码注释的最佳实践
  • 原文地址:https://www.cnblogs.com/neversayno/p/5213542.html
Copyright © 2011-2022 走看看