博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-79 Word Search
阅读量:4590 次
发布时间:2019-06-09

本文共 1190 字,大约阅读时间需要 3 分钟。

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 =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]

word = "ABCCED", -> returns true,

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

 

题意:在矩阵中,相邻的元素可以是上、下、左、右的元素。同时要求矩阵中的同一个字符不能重复匹配。

 

思路:使用DFS遍历矩阵,直到遍历完字符串,说明匹配。但是需要记录矩阵中哪个字符是已经匹配过的。

由于英文字符范围是0~127,因此遍历某个字符后,进行c^=128操作,该字符在后续匹配中就不会再次

匹配到,从而实现标记的效果。在回溯的时候需要将标记的字符还原。

 

代码如下:

public boolean exist(char[][] board, String word) {        for(int i=0; i
=board.length || y>=board[0].length || board[x][y] != word.charAt(index)) return false; board[x][y] ^= 128; boolean exist = exist(board, x-1, y, word, index+1) || exist(board, x+1, y, word, index+1) || exist(board, x, y-1, word, index+1) || exist(board, x, y+1, word, index+1) ; board[x][y] ^= 128; return exist; }

 

转载于:https://www.cnblogs.com/linxiong/p/4489224.html

你可能感兴趣的文章
蓝牙模块选择经验谈
查看>>
java中==和equals
查看>>
CCActionPageTurn3D
查看>>
python random
查看>>
esp32-智能语音-cli(调试交互命令)
查看>>
netty与MQ使用心得
查看>>
jquery 实现3d切割轮播图
查看>>
学习spring cloud 笔记
查看>>
字符串截取,SubString
查看>>
Android: 网络随时需要在3G和Wifi切换,网络程序需要注意
查看>>
ajax调用servlet
查看>>
IText 生成横向的doc文档
查看>>
认识了个外国友人!
查看>>
对Cookie进行增删改查
查看>>
MySQL sql语句获取当前日期|时间|时间戳
查看>>
微信支付官方SDK V3 .NET版的坑
查看>>
Python(一)list tuple dict set
查看>>
什么是死锁,简述死锁发生的四个必要条件,如何避免与预防死锁
查看>>
hdu4651(广义五边形数 & 分割函数1)
查看>>
python iter,迭代器&dict,字典详解
查看>>