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

    }

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    600E
    题解报告:hdu 1124 Factorial(求N!尾数有多少个0。)
    求N!尾数有多少个0。
    poj 2185 Milking Grid(二维kmp)
    poj 2752 Seek the Name, Seek the Fame(kmp前缀表prefix_table的运用)
    hdu 1686 Oulipo(裸KMP)
    2018 ACM 国际大学生程序设计竞赛上海大都会赛重现赛-B-Perfect Numbers(完数)
    2018 ACM 国际大学生程序设计竞赛上海大都会赛重现赛-K-Matrix Multiplication(矩阵乘法)
    poj 3468 A Simple Problem with Integers(线段树区间lazy标记修改or树状数组)
    hdu 1698 Just a Hook(线段树区间lazy标记修改)
  • 原文地址:https://www.cnblogs.com/neversayno/p/5213542.html
Copyright © 2011-2022 走看看