zoukankan      html  css  js  c++  java
  • 79. Word Search

    Given a 2D board and a word, find if the word exists in the grid.

    The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

    For example,
    Given board =

    [
      ['A','B','C','E'],
      ['S','F','C','S'],
      ['A','D','E','E']
    ]
    

    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false.

    题目含义:给定一个字母组成的矩阵,看看相邻的字母能否组成一个给定的单词,每个位置的字母只能使用一次

     1     private boolean exist(char[][] board, int x, int y, char[] word, int i) {
     2         if (i == word.length) return true;
     3         if (x < 0 || y < 0 || x == board.length || y == board[x].length) return false;
     4         if (board[x][y] != word[i]) return false;
     5         board[x][y] ^= 256;    //将当前位置变得和任何字符都不相等,避免遍历周边4个节点的是否,又找到本节点
     6         boolean exist = exist(board, x, y + 1, word, i + 1)
     7                 || exist(board, x, y - 1, word, i + 1)
     8                 || exist(board, x + 1, y, word, i + 1)
     9                 || exist(board, x - 1, y, word, i + 1);
    10         board[x][y] ^= 256;    //周边4个节点都遍历完了,可以恢复本节点了
    11         return exist;
    12     }
    13     
    14     public boolean exist(char[][] board, String word) {
    15         char[] w = word.toCharArray();
    16         for (int x = 0; x < board.length; x++) {
    17             for (int y = 0; y < board[x].length; y++) {
    18                 if (exist(board, x, y, w, 0)) return true;
    19             }
    20         }
    21         return false;
    22     }
  • 相关阅读:
    利用wget下载文件,并保存到指定目录
    tar命令详解
    Ubuntu 16.04中安装Chromium浏览器
    怎么打开unity tweak tool
    WPS for linux不能使用中文输入法
    Window7 驱动编程环境配置
    Windows内核 字符串基本操作
    Windows内核 语言选择注意点
    Windows内核 内存管理基本概念
    Windows内核 WDM驱动程序的基本结构和实例
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7676126.html
Copyright © 2011-2022 走看看