【題目描述】
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.
給出一個二維的字母板和一個單詞尝丐,尋找字母板網(wǎng)格中是否存在這個單詞罢绽。
單詞可以由按順序的相鄰單元的字母組成,其中相鄰單元指的是水平或者垂直方向相鄰车摄。每個單元中的字母最多只能使用一次寺谤。
【題目鏈接】
www.lintcode.com/en/problem/word-search/
【題目解析】
基本思路比較簡單:從board上每一個點(diǎn)出發(fā)希俩,用depth first search (DFS)上下左右四方向搜索匹配的word档押。需要注意到幾點(diǎn):
1逞力、考慮board的邊界
2煌往、cell是否已經(jīng)被遍歷過(臨時轉(zhuǎn)換為特定標(biāo)識字符倾哺,比如'#',recursion返回后再重置回原來的值刽脖,這樣可以省去額外開辟二維數(shù)組visited[i][j]的空間復(fù)雜度)
3羞海、搜索結(jié)束的標(biāo)志是k == word.length()
【參考答案】