Skip to content

Commit b13b64e

Browse files
committed
feat: update solutions to lcof problems: No.12,13
- 面试题12. 矩阵中的路径 - 面试题13. 机器人的运动范围
1 parent 9ae12d5 commit b13b64e

File tree

6 files changed

+118
-119
lines changed

6 files changed

+118
-119
lines changed

lcof/面试题12. 矩阵中的路径/README.md

+24-23
Original file line numberDiff line numberDiff line change
@@ -214,24 +214,24 @@ public:
214214
function exist(board: string[][], word: string): boolean {
215215
const m = board.length;
216216
const n = board[0].length;
217-
const dfs = (y: number, x: number, i: number) => {
218-
if (i === word.length) {
219-
return true;
220-
}
221-
if ((board[y] || [])[x] !== word[i]) {
217+
const dfs = (i: number, j: number, k: number) => {
218+
if ((board[i] ?? [])[j] !== word[k]) {
222219
return false;
223220
}
224-
const temp = board[y][x];
225-
board[y][x] = '';
221+
if (++k === word.length) {
222+
return true;
223+
}
224+
const temp = board[i][j];
225+
board[i][j] = ' ';
226226
if (
227-
dfs(y + 1, x, i + 1) ||
228-
dfs(y, x + 1, i + 1) ||
229-
dfs(y - 1, x, i + 1) ||
230-
dfs(y, x - 1, i + 1)
227+
dfs(i + 1, j, k) ||
228+
dfs(i, j + 1, k) ||
229+
dfs(i - 1, j, k) ||
230+
dfs(i, j - 1, k)
231231
) {
232232
return true;
233233
}
234-
board[y][x] = temp;
234+
board[i][j] = temp;
235235
return false;
236236
};
237237
for (let i = 0; i < m; i++) {
@@ -249,23 +249,24 @@ function exist(board: string[][], word: string): boolean {
249249

250250
```rust
251251
impl Solution {
252-
fn dfs(board: &mut Vec<Vec<char>>, chars: &Vec<char>, y: usize, x: usize, i: usize) -> bool {
253-
if board[y][x] != chars[i] {
252+
fn dfs(board: &mut Vec<Vec<char>>, chars: &Vec<char>, i: usize, j: usize, mut k: usize) -> bool {
253+
if board[i][j] != chars[k] {
254254
return false;
255255
}
256-
if i + 1 == chars.len() {
256+
k += 1;
257+
if k == chars.len() {
257258
return true;
258259
}
259-
let temp = board[y][x];
260-
board[y][x] = ' ';
261-
if y != 0 && Solution::dfs(board, chars, y - 1, x, i + 1)
262-
|| x != 0 && Solution::dfs(board, chars, y, x - 1, i + 1)
263-
|| y != board.len() - 1 && Solution::dfs(board, chars, y + 1, x, i + 1)
264-
|| x != board[0].len() - 1 && Solution::dfs(board, chars, y, x + 1, i + 1)
260+
let temp = board[i][j];
261+
board[i][j] = ' ';
262+
if i != 0 && Self::dfs(board, chars, i - 1, j, k)
263+
|| j != 0 && Self::dfs(board, chars, i, j - 1, k)
264+
|| i != board.len() - 1 && Self::dfs(board, chars, i + 1, j, k)
265+
|| j != board[0].len() - 1 && Self::dfs(board, chars, i, j + 1, k)
265266
{
266267
return true;
267268
}
268-
board[y][x] = temp;
269+
board[i][j] = temp;
269270
false
270271
}
271272

@@ -275,7 +276,7 @@ impl Solution {
275276
let chars = word.chars().collect::<Vec<char>>();
276277
for i in 0..m {
277278
for j in 0..n {
278-
if Solution::dfs(&mut board, &chars, i, j, 0) {
279+
if Self::dfs(&mut board, &chars, i, j, 0) {
279280
return true;
280281
}
281282
}

lcof/面试题12. 矩阵中的路径/Solution.rs

+12-11
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,22 @@
11
impl Solution {
2-
fn dfs(board: &mut Vec<Vec<char>>, chars: &Vec<char>, y: usize, x: usize, i: usize) -> bool {
3-
if board[y][x] != chars[i] {
2+
fn dfs(board: &mut Vec<Vec<char>>, chars: &Vec<char>, i: usize, j: usize, mut k: usize) -> bool {
3+
if board[i][j] != chars[k] {
44
return false;
55
}
6-
if i + 1 == chars.len() {
6+
k += 1;
7+
if k == chars.len() {
78
return true;
89
}
9-
let temp = board[y][x];
10-
board[y][x] = ' ';
11-
if y != 0 && Solution::dfs(board, chars, y - 1, x, i + 1)
12-
|| x != 0 && Solution::dfs(board, chars, y, x - 1, i + 1)
13-
|| y != board.len() - 1 && Solution::dfs(board, chars, y + 1, x, i + 1)
14-
|| x != board[0].len() - 1 && Solution::dfs(board, chars, y, x + 1, i + 1)
10+
let temp = board[i][j];
11+
board[i][j] = ' ';
12+
if i != 0 && Self::dfs(board, chars, i - 1, j, k)
13+
|| j != 0 && Self::dfs(board, chars, i, j - 1, k)
14+
|| i != board.len() - 1 && Self::dfs(board, chars, i + 1, j, k)
15+
|| j != board[0].len() - 1 && Self::dfs(board, chars, i, j + 1, k)
1516
{
1617
return true;
1718
}
18-
board[y][x] = temp;
19+
board[i][j] = temp;
1920
false
2021
}
2122

@@ -25,7 +26,7 @@ impl Solution {
2526
let chars = word.chars().collect::<Vec<char>>();
2627
for i in 0..m {
2728
for j in 0..n {
28-
if Solution::dfs(&mut board, &chars, i, j, 0) {
29+
if Self::dfs(&mut board, &chars, i, j, 0) {
2930
return true;
3031
}
3132
}

lcof/面试题12. 矩阵中的路径/Solution.ts

+12-12
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
function exist(board: string[][], word: string): boolean {
22
const m = board.length;
33
const n = board[0].length;
4-
const dfs = (y: number, x: number, i: number) => {
5-
if (i === word.length) {
6-
return true;
7-
}
8-
if ((board[y] || [])[x] !== word[i]) {
4+
const dfs = (i: number, j: number, k: number) => {
5+
if ((board[i] ?? [])[j] !== word[k]) {
96
return false;
107
}
11-
const temp = board[y][x];
12-
board[y][x] = '';
8+
if (++k === word.length) {
9+
return true;
10+
}
11+
const temp = board[i][j];
12+
board[i][j] = ' ';
1313
if (
14-
dfs(y + 1, x, i + 1) ||
15-
dfs(y, x + 1, i + 1) ||
16-
dfs(y - 1, x, i + 1) ||
17-
dfs(y, x - 1, i + 1)
14+
dfs(i + 1, j, k) ||
15+
dfs(i, j + 1, k) ||
16+
dfs(i - 1, j, k) ||
17+
dfs(i, j - 1, k)
1818
) {
1919
return true;
2020
}
21-
board[y][x] = temp;
21+
board[i][j] = temp;
2222
return false;
2323
};
2424
for (let i = 0; i < m; i++) {

lcof/面试题13. 机器人的运动范围/README.md

+45-41
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,20 @@
3535

3636
**流程**
3737

38-
1. `(0,0)` 开始。
39-
2. 根据公式判断 `(i,j)` 是否可进入:
40-
- 可进入,继续往右(`(i, j + 1)`)往下(`(i + 1, j)`)重新执行流程 2。
41-
- 不可进入,退出结算。
42-
3. 计算可进入方格的数量,返回即可。
38+
1. `(0,0)` 开始。
39+
40+
2. 根据公式判断 `(i, j)` 是否可进入:
41+
42+
- 可进入,并继续往右 `(i, j + 1)` 往下 `(i + 1, j)` 重新执行流程 2。
43+
- 不可进入,退出结算。
44+
45+
3. 计算可进入区域的数量,返回即可。
4346

4447
**剪枝**
4548

4649
对于已进入的方格,需要防止多次进入,否则会导致指数级耗时。
4750

48-
在确定方格可进入后,给方格加上标记。判断一个方格可进入性之前,先查看是否存在对应的标记,存在标记时及时退出。
51+
在确定方格可进入后,给方格加上标记。判断一个方格可进入之前,先查看是否存在对应的标记,存在标记时及时退出。
4952

5053
记录方式不限数组与哈希表。
5154

@@ -171,20 +174,19 @@ public:
171174
```ts
172175
function movingCount(m: number, n: number, k: number): number {
173176
const set = new Set();
174-
const dfs = (y: number, x: number) => {
175-
if (y === m || x === n || set.has(`${y},${x}`)) {
177+
const dfs = (i: number, j: number) => {
178+
const key = `${i},${j}`;
179+
if (
180+
i === m ||
181+
j === n ||
182+
set.has(key) ||
183+
`${i}${j}`.split('').reduce((r, v) => r + Number(v), 0) > k
184+
) {
176185
return;
177186
}
178-
let count = 0;
179-
const str = `${y}${x}`;
180-
for (const c of str) {
181-
count += Number(c);
182-
}
183-
if (count <= k) {
184-
set.add(`${y},${x}`);
185-
dfs(y + 1, x);
186-
dfs(y, x + 1);
187-
}
187+
set.add(key);
188+
dfs(i + 1, j);
189+
dfs(i, j + 1);
188190
};
189191
dfs(0, 0);
190192
return set.size;
@@ -197,25 +199,26 @@ function movingCount(m: number, n: number, k: number): number {
197199

198200
```rust
199201
use std::collections::{HashSet, VecDeque};
200-
201202
impl Solution {
202203
pub fn moving_count(m: i32, n: i32, k: i32) -> i32 {
203-
let mut deque = VecDeque::new();
204204
let mut set = HashSet::new();
205-
deque.push_back([0, 0]);
206-
while let Some([y, x]) = deque.pop_front() {
207-
if y < m && x < n && !set.contains(&format!("{},{}", y, x)) {
208-
let str = format!("{}{}", y, x);
209-
let mut count = 0;
210-
for c in str.chars() {
211-
count += c.to_string().parse::<i32>().unwrap();
212-
}
213-
if count <= k {
214-
set.insert(format!("{},{}", y, x));
215-
deque.push_back([y + 1, x]);
216-
deque.push_back([y, x + 1]);
217-
}
205+
let mut queue = VecDeque::new();
206+
queue.push_back([0, 0]);
207+
while let Some([i, j]) = queue.pop_front() {
208+
let key = format!("{},{}", i, j);
209+
if i == m
210+
|| j == n
211+
|| set.contains(&key)
212+
|| k < format!("{}{}", i, j)
213+
.chars()
214+
.map(|c| c.to_string().parse::<i32>().unwrap())
215+
.sum::<i32>()
216+
{
217+
continue;
218218
}
219+
set.insert(key);
220+
queue.push_back([i + 1, j]);
221+
queue.push_back([i, j + 1]);
219222
}
220223
set.len() as i32
221224
}
@@ -226,20 +229,21 @@ impl Solution {
226229

227230
```rust
228231
impl Solution {
229-
fn dfs(sign: &mut Vec<Vec<bool>>, k: usize, y: usize, x: usize) -> i32 {
230-
if y == sign.len()
231-
|| x == sign[0].len()
232-
|| sign[y][x]
233-
|| x % 10 + x / 10 % 10 + y % 10 + y / 10 % 10 > k
232+
fn dfs(sign: &mut Vec<Vec<bool>>, k: usize, i: usize, j: usize) -> i32 {
233+
if i == sign.len()
234+
|| j == sign[0].len()
235+
|| sign[i][j]
236+
|| j % 10 + j / 10 % 10 + i % 10 + i / 10 % 10 > k
234237
{
235238
return 0;
236239
}
237-
sign[y][x] = true;
238-
1 + Solution::dfs(sign, k, y + 1, x) + Solution::dfs(sign, k, y, x + 1)
240+
sign[i][j] = true;
241+
1 + Self::dfs(sign, k, i + 1, j) + Self::dfs(sign, k, i, j + 1)
239242
}
243+
240244
pub fn moving_count(m: i32, n: i32, k: i32) -> i32 {
241245
let mut sign = vec![vec![false; n as usize]; m as usize];
242-
Solution::dfs(&mut sign, k as usize, 0, 0)
246+
Self::dfs(&mut sign, k as usize, 0, 0)
243247
}
244248
}
245249
```
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,18 @@
1-
use std::collections::{HashSet, VecDeque};
2-
31
impl Solution {
4-
pub fn moving_count(m: i32, n: i32, k: i32) -> i32 {
5-
let mut deque = VecDeque::new();
6-
let mut set = HashSet::new();
7-
deque.push_back([0, 0]);
8-
while let Some([y, x]) = deque.pop_front() {
9-
if y < m && x < n && !set.contains(&format!("{},{}", y, x)) {
10-
let str = format!("{}{}", y, x);
11-
let mut count = 0;
12-
for c in str.chars() {
13-
count += c.to_string().parse::<i32>().unwrap();
14-
}
15-
if count <= k {
16-
set.insert(format!("{},{}", y, x));
17-
deque.push_back([y + 1, x]);
18-
deque.push_back([y, x + 1]);
19-
}
20-
}
2+
fn dfs(sign: &mut Vec<Vec<bool>>, k: usize, i: usize, j: usize) -> i32 {
3+
if i == sign.len()
4+
|| j == sign[0].len()
5+
|| sign[i][j]
6+
|| j % 10 + j / 10 % 10 + i % 10 + i / 10 % 10 > k
7+
{
8+
return 0;
219
}
22-
set.len() as i32
10+
sign[i][j] = true;
11+
1 + Self::dfs(sign, k, i + 1, j) + Self::dfs(sign, k, i, j + 1)
12+
}
13+
14+
pub fn moving_count(m: i32, n: i32, k: i32) -> i32 {
15+
let mut sign = vec![vec![false; n as usize]; m as usize];
16+
Self::dfs(&mut sign, k as usize, 0, 0)
2317
}
2418
}

lcof/面试题13. 机器人的运动范围/Solution.ts

+11-12
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
function movingCount(m: number, n: number, k: number): number {
22
const set = new Set();
3-
const dfs = (y: number, x: number) => {
4-
if (y === m || x === n || set.has(`${y},${x}`)) {
3+
const dfs = (i: number, j: number) => {
4+
const key = `${i},${j}`;
5+
if (
6+
i === m ||
7+
j === n ||
8+
set.has(key) ||
9+
`${i}${j}`.split('').reduce((r, v) => r + Number(v), 0) > k
10+
) {
511
return;
612
}
7-
let count = 0;
8-
const str = `${y}${x}`;
9-
for (const c of str) {
10-
count += Number(c);
11-
}
12-
if (count <= k) {
13-
set.add(`${y},${x}`);
14-
dfs(y + 1, x);
15-
dfs(y, x + 1);
16-
}
13+
set.add(key);
14+
dfs(i + 1, j);
15+
dfs(i, j + 1);
1716
};
1817
dfs(0, 0);
1918
return set.size;

0 commit comments

Comments
 (0)