力扣 79 單詞搜尋

2021-10-23 13:17:06 字數 1662 閱讀 8987

題目:(直接看劍指offer第六十五題矩陣中的路徑)

給定乙個二維網格和乙個單詞,找出該單詞是否存在於網格中。

單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中「相鄰」單元格是那些水平相鄰或垂直相鄰的單元格。同乙個單元格內的字母不允許被重複使用。

示例:board =

[['a','b','c','e'],

['s','f','c','s'],

['a','d','e','e']

]給定 word = "abcced", 返回 true

給定 word = "see", 返回 true

給定 word = "abcb", 返回 false

題解:回溯其實就是 dfs ,兩者沒有太大的差別。dfs 用於搜尋就叫回溯,搜尋的時候強調使用乙份變數去搜尋所有的可能性,所以需要狀態重置(true變為false或者addlast變為removelast等),由於要強調這個事情,所以叫回溯。

「我們在之前做了什麼,這一步做相應的逆操作,這就叫回溯。」

所以我的結論是:使用乙份變數去搜尋的 dfs 被稱作回溯,回溯強調搜尋,dfs 強調遍歷。

package test;

class solution , , , };//偏移量陣列,上左右下

// 盤面上有多少行

private int m;

// 盤面上有多少列

private int n;

private string word;

private char board;

public boolean exist(char board, string word)

n = board[0].length;

marked = new boolean[m][n];

this.word = word;

this.board = board;

for (int i = 0; i < m; i++) }}

return false;

}private boolean dfs(int i, int j, int start)

if (board[i][j] == word.charat(start)) }}

marked[i][j] = false;

}return false;

}private boolean inarea(int x, int y)

}public class main,,};

string word = "aab";

// char board =

// ,

// ,

//

// };

//// string word = "abcced";

// char board = };

// string word = "ba";

solution s = new solution();

boolean p = s.exist(board, word);

system.out.print(" " + p);

}}

力扣79 單詞搜尋

給定乙個二維網格和乙個單詞,找出該單詞是否存在於網格中。單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中 相鄰 單元格是那些水平相鄰或垂直相鄰的單元格。同乙個單元格內的字母不允許被重複使用。示例 board a b c e s f c s a d e e 給定 word abcced 返回 ...

力扣79 單詞搜尋

class solution return false public boolean existhelper char board,boolean used,char word,int idx,int col,int row if used row col true board row col wo...

力扣79 單詞搜尋

給定乙個二維網格和乙個單詞,找出該單詞是否存在於網格中。單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中 相鄰 單元格是那些水平相鄰或垂直相鄰的單元格。同乙個單元格內的字母不允許被重複使用。示例 board a b c e s f c s a d e e 給定 word abcced 返回 ...