1629. 按鍵持續(xù)時間最長的鍵
668
2022-05-28
給定一個二維網(wǎng)格?board?和一個字典中的單詞列表 words,找出所有同時在二維網(wǎng)格和字典中出現(xiàn)的單詞。
單詞必須按照字母順序,通過相鄰的單元格內(nèi)的字母構(gòu)成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個單元格內(nèi)的字母在一個單詞中不允許被重復(fù)使用。
示例:
輸入:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
輸出:?["eat","oath"]
說明:
你可以假設(shè)所有輸入都由小寫字母 a-z?組成。
思路:上一道題改一下,把每一個單詞都判斷一下即可。
class Solution {
private boolean[][] marked;
// x-1,y
// x,y-1 x,y x,y+1
// x+1,y
private int[][] direction = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
// 盤面上有多少行
private int m;
// 盤面上有多少列
private int n;
private String word;
private char[][] board;
//答案數(shù)組
Set
//判斷一個字符
public List
m = board.length;
if (m == 0)return null;
n = board[0].length;
marked = new boolean[m][n];
this.board = board;
for(String s:words){
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
marked[i][j]=false;
this.word = s;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (dfs(i, j, 0))
ans.add(s);
}
List
Collections.sort(ansList);
return ansList;
}
private boolean dfs(int i, int j, int start) {
if (start == word.length() - 1) {
return board[i][j] == word.charAt(start);
}
if (board[i][j] == word.charAt(start)) {
marked[i][j] = true;
for (int k = 0; k < 4; k++) {
int newX = i + direction[k][0];
int newY = j + direction[k][1];
if (newX >= 0 && newX < m && newY >= 0 && newY < n && !marked[newX][newY]) {
if (dfs(newX, newY, start + 1)) {
return true;
}
}
}
marked[i][j] = false;
}
return false;
}
}
數(shù)據(jù)結(jié)構(gòu)
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實后本網(wǎng)站將在24小時內(nèi)刪除侵權(quán)內(nèi)容。