用 JavaScript 查詢矩陣中的單詞
我們需要編寫一個 JavaScript 函式,它接收一個字元陣列陣列作為第一個引數和一個字串作為第二個引數。
該函式應找出矩陣中是否存在字元,其非重複組合產生了作為第二個引數提供給函式的字串。
如果存在這樣的組合,我們的函式應返回 true,否則返回 false。
例如 −
如果輸入陣列和字串為 −
const arr = [ ['s', 'd', 'k', 'e'], ['j', 'm', 'o', 'w'], ['y', 'n', 'l'] ]; const str = 'don';
那麼輸出應為 −
const output = false;
示例
程式碼如下 −
const arr = [
['s', 'd', 'k', 'e'],
['j', 'm', 'o', 'width'],
['y', 'n', 'l']
];
const str = 'don';
const containsWord = (arr = [], str = '') => {
if (arr.length === 0){
return false;
};
const height = arr.length;
const width = arr[0].length;
const dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]];
const tryWord = (x, y, k) => {
if (arr[x][y] !== str[k]) return false;
if (k === str.length - 1) return true;
arr[x][y] = '*';
for (const [dx, dy] of dirs) {
const i = x + dx;
const j = y + dy;
if (i >= 0 && i < height && j >= 0 && j < width) {
if (tryWord(i, j, k + 1)) return true;
}
}
arr[x][y] = str[k]; // reset
return false;
};
for (let i = 0; i < height; i++) {
for (let j = 0; j < width; j++) {
if (tryWord(i, j, 0)) return true;
}
}
return false;
};
console.log(containsWord(arr, str));輸出
控制檯輸出如下 −
false
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP