深入解析:【双机位A卷】华为OD笔试之【回溯】双机位A-找到它【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
可上 欧弟OJ系统 练习华子OD、大厂真题
绿色聊天软件戳od1441了解算法冲刺训练(备注【CSDN】否则不通过)
文章目录
相关推荐阅读
- 【华为OD机考正在更新】2025年双机位A卷真题【完全原创题解 | 详细考点分类 | 不断更新题目 | 六种主流语言Py+Java+Cpp+C+Js+Go】
- 【华为OD机考】2025C+2025B+2024E+D卷真题【完全原创题解 | 详细考点分类 | 不断更新题目】
- 【华为OD笔试】双机位A+2025C+2025B+2024E+D卷真题机考套题汇总【真实反馈,不断更新,限时免费】
- 【华为OD笔试】2024E+D卷命题规律解读【分析500+场OD笔试考点总结】
- 【华为OD流程】性格测试选项+注意事项】
题目练习网址:【回溯】双机位A-找到它
题目描述与示例
题目描述
找到它是个小游戏,你需要在一个矩阵中找到给定的单词
假设给定单词HELLOWORLD,在矩阵中只要能找HELLOWORLD就算通过
注意区分英文字母大小写,并且你只能上下左右行走,不能走回头路
输入描述
输入第一行包含两个整数N M (0 < N, M < 21)
分别表示N行M列的矩阵
第二行是长度不超过100的单词W
在整个矩阵中给定单词W只会出现一次
从第3行到第N+2是只包含大小写英文字母的长度为M的字符串矩阵
输出描述
如果能在矩阵中连成给定的单词,则输出给定单词首字母在矩阵中的位置为第几行第几列 否则输出 NO
示例一
输入
5 5
HELLOWORLD
CPUCY
EKLQH
CHELL
LROWO
DGRBC
输出
3 2
示例二
输入
5 5
Helloworld
CPUCh
wolle
orldO
EKLQo
PGRBC
输出
NO
解题思路
注意,本题和LeetCode79. 单词搜索几乎完全一致,唯一的区别在于前者只要求判断是否能够找到该单词,本题还需要输出起始位置。
状态更新和回滚写在横向遍历for循环内的回溯写法
我们需要思考的是,对于这种二维网格如何进行回溯?换句话说,如何构建回溯函数?
在回溯过程中我们需要知道以下信息:
- 当前进行到了单词中的哪一个字符?
- 当前在网格中搜索到了哪一个位置?
- 由于网格中的字符不能重复使用,那么哪一些字符是已经使用过的?
- 是否已经在网格中找到了这个单词?
对于第一点,我们的回溯函数中需要存在参数word_idx,来表示待搜索的单词此时遍历到的索引位置。
对于第二点,我们的回溯函数需要传入当前搜索的点的位置(x, y)
对于第三点,这个在二维网格类型的搜索问题中是非常常用的技巧,即构建一个大小和grid一样的check_list
对于第四点,我们可以直接声明一个全局变量isFind来表示是否已经找到该单词
除了这些参数之外,我们还需要传入二维矩阵grid本身,它的大小N和M等等。
容易构建出回溯函数如下
DIRECTIONS = [(0,1), (1,0), (-1,0), (0,-1)]
def backtracking(grid, N, M, check_list, x, y, word, word_idx):
global isFind
if word_idx == len(word) - 1:
isFind = True
return
for dx, dy in DIRECTIONS:
nx, ny = x+dx, y+dy
if (0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and
check_list[nx][ny] == False and grid[nx][ny] == word[word_idx+1]):
check_list[nx][ny] = True
backtracking(grid, N, M, check_list, nx, ny, word, word_idx+1)
check_list[nx][ny] = False
容易发现,此处回溯函数的写法,和我们用DFS做二维网格搜索类型的题目是非常类似的。
换句话说,在当前点(x, y)的近邻点上下左右四个方向的选取的这个for循环,实际上就对应着回溯过程中状态树的横向遍历。
和常规DFS解法的区别在于,我们现在搜索的是一条路径,所以我们需要在递归调用backtracking()函数的前后,进行check_list[nx][ny]的状态更新和回滚,来表示近邻点(nx, ny)已经被使用过以及回滚之后再次可以被使用的情况。
在递归调用回溯函数的时候,我们需要将下一个点(nx, ny)以及word的下一个字符索引word_idx+1传入函数中。
回溯的终止条件也非常简单,就是当word_idx已经等于len(word)-1了,说明整个word的所有字符都能够在二维网格中找到,那么修改isFind为True,同时退出搜索。
而递归入口则需要这样调用
isFind = False
check_list = [[False] * M for _ in range(N)]
for i in range(N):
for j in range(M):
if grid[i][j] == word[0]:
check_list[i][j] = True
backtracking(grid, N, M, check_list, i, j, word, 0)
check_list[i][j] = False
if isFind:
print("{} {}".format(i+1, j+1))
break
if isFind:
break
注意到,由于在回溯函数中修改check_list始终是对(nx, ny)进行修改,所以我们在做起始点搜索的双重循环的时候,在递归函数入口处,需要对起始点(i, j)额外地进行check_list的状态更新和回滚。
状态更新和回滚写在横向遍历for循环外的回溯写法
如果你想直接修改check_list[x][y]而不是修改check_list[nx][ny],那么回溯函数也可以改成这样
DIRECTIONS = [(0,1), (1,0), (-1,0), (0,-1)]
def backtracking(grid, N, M, check_list, x, y, word, word_idx):
global isFind
if word_idx == len(word) - 1:
isFind = True
return
check_list[x][y] = True
for dx, dy in DIRECTIONS:
nx, ny = x+dx, y+dy
if (0 <= nx < len(grid) and 0 <= ny < len(grid[0])
and check_list[nx][ny] == False and grid[nx][ny] == word[word_idx+1]):
backtracking(grid, N, M, check_list, nx, ny, word, word_idx+1)
check_list[x][y] = False
这样就跟常规的DFS解法更加接近,但和常规的回溯题目的相似性就没那么高了。
因为状态更新和回滚写在了横向遍历for循环的外部。
对应的,由于此处状态的是(x, y)而非(nx, ny),那么在递归入口处就可以不用单独进行(i, j)的更新了。即递归入口可以写为
isFind = False
check_list = [[False] * M for _ in range(N)]
for i in range(N):
for j in range(M):
if grid[i][j] == word[0]:
backtracking(grid, N, M, check_list, i, j, word, 0)
if isFind:
print("{} {}".format(i+1, j+1))
break
if isFind:
break
代码
Python
# 欢迎来到「欧弟算法 - 华为OD全攻略」,收录华为OD题库、面试指南、八股文与学员案例!
# 地址:https://www.odalgo.com
# 华为OD机试刷题网站:https://www.algomooc.com
# 添加微信 278166530 获取华为 OD 笔试真题题库和视频
# 题目:2024E/2025C/双机位A-找到它
# 分值:200
# 作者:许老师-闭着眼睛学数理化
# 算法:回溯
# 代码看不懂的地方,请直接在群上提问
# 全局的方向数组,表示上下左右移动四个方向
DIRECTIONS = [(0,1), (1,0), (-1,0), (0,-1)]
# 构建回溯函数,各个参数的含义为
# grid: 原二维矩阵
# N,M: 原二维矩阵的行数、列数
# check_list: 大小和grid一样的检查列表,用于判断某个点是否已经检查过
# x,y: 当前在grid中的点的坐标
# word: 待搜索的单词
# word_idx: 待搜索的单词此时遍历到的索引位置
def backtracking(grid, N, M, check_list, x, y, word, word_idx):
# 声明全局变量isFind
global isFind
# 若此时word_idx等于word的长度-1
# 说明word中的所有字母都在grid中找到了
# 修改isFind为True,同时终止递归
if word_idx == len(word) - 1:
isFind = True
return
# 遍历四个方向,获得点(x,y)的近邻点(nx,ny)
for dx, dy in DIRECTIONS:
nx, ny = x+dx, y+dy
# (nx,ny)必须满足以下三个条件,才可以继续进行回溯函数的递归调用
# 1. 不越界;2. 尚未检查过;
# 3.在grid中的值grid[nx][ny]为word的下一个字符word[word_idx+1]
if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and check_list[nx][ny] == False and grid[nx][ny] == word[word_idx+1]:
# 状态更新,将点(nx,ny)在check_list中的状态更新为True
check_list[nx][ny] = True
# 回溯,将点(nx,ny)传入回溯函数中,注意此时word_idx需要+1
backtracking(grid, N, M, check_list, nx, ny, word, word_idx+1)
# 回滚,将点(nx,ny)在check_list中的状态重新修改回False
check_list[nx][ny] = False
# 输入行数和列数
N, M = map(int, input().split())
# 输入待查找的单词
word = input()
# 构建二维网格
grid = list()
for _ in range(N):
grid.append(input())
# 构建全局变量isFind,初始化为False
isFind = False
# 构建大小和grid一样的检查数组check_list
# 用于避免出现重复检查的情况
check_list = [[False] * M for _ in range(N)]
# 双重遍历整个二维网格grid
for i in range(N):
for j in range(M):
# 找到点(i,j)等于word的第一个字母
# 则点(i,j)可以作为递归的起始位置
if grid[i][j] == word[0]:
# 将点(i,j)在check_list中设置为已检查过
check_list[i][j] = True
# 回溯函数递归入口
backtracking(grid, N, M, check_list, i, j, word, 0)
# 将点(i,j)在check_list中重置为未检查过,因为本次回溯不一定找到答案
check_list[i][j] = False
# 如果在回溯中,全局变量isFind被改为True,说明找到了单词
if isFind:
# 输出行数和列数,注意在问题中行数和列数是从1开始计数的
# 所以存在一个+1操作
print("{} {}".format(i+1, j+1))
# 同时可以直接退出循环
break
if isFind:
break
if not isFind:
print("NO")
Java
import java.util.Scanner;
public class Main {
// Global directions array to represent four directions: up, down, left, right
private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
private static boolean isFind = false;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int M = scanner.nextInt();
scanner.nextLine(); // Consume newline
String word = scanner.nextLine();
char[][] grid = new char[N][M];
for (int i = 0; i < N; i++) {
String row = scanner.nextLine();
for (int j = 0; j < M; j++) {
grid[i][j] = row.charAt(j);
}
}
boolean[][] checkList = new boolean[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (grid[i][j] == word.charAt(0)) {
checkList[i][j] = true;
backtracking(grid, N, M, checkList, i, j, word, 0);
checkList[i][j] = false;
if (isFind) {
System.out.println((i + 1) + " " + (j + 1));
return;
}
}
}
}
if (!isFind) {
System.out.println("NO");
}
}
private static void backtracking(char[][] grid, int N, int M, boolean[][] checkList, int x, int y, String word, int wordIdx) {
if (wordIdx == word.length() - 1) {
isFind = true;
return;
}
for (int[] dir : DIRECTIONS) {
int nx = x + dir[0];
int ny = y + dir[1];
if (nx >= 0 && nx < N && ny >= 0 && ny < M && !checkList[nx][ny] && grid[nx][ny] == word.charAt(wordIdx + 1)) {
checkList[nx][ny] = true;
backtracking(grid, N, M, checkList, nx, ny, word, wordIdx + 1);
checkList[nx][ny] = false;
}
}
}
}
C++
#include <iostream>
#include <vector>
using namespace std;
// Global directions array to represent four directions: up, down, left, right
const vector<pair<int, int>> DIRECTIONS = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
bool isFind = false;
// Backtracking function
void backtracking(vector<vector<char>>& grid, int N, int M, vector<vector<bool>>& checkList, int x, int y, string& word, int wordIdx) {
if (wordIdx == word.length() - 1) {
isFind = true;
return;
}
for (const auto& dir : DIRECTIONS) {
int nx = x + dir.first;
int ny = y + dir.second;
if (nx >= 0 && nx < N && ny >= 0 && ny < M && !checkList[nx][ny] && grid[nx][ny] == word[wordIdx + 1]) {
checkList[nx][ny] = true;
backtracking(grid, N, M, checkList, nx, ny, word, wordIdx + 1);
checkList[nx][ny] = false;
}
}
}
int main() {
int N, M;
cin >> N >> M;
string word;
cin >> word;
vector<vector<char>> grid(N, vector<char>(M));
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cin >> grid[i][j];
}
}
vector<vector<bool>> checkList(N, vector<bool>(M, false));
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (grid[i][j] == word[0]) {
checkList[i][j] = true;
backtracking(grid, N, M, checkList, i, j, word, 0);
checkList[i][j] = false;
if (isFind) {
cout << i + 1 << " " << j + 1 << endl;
return 0;
}
}
}
}
if (!isFind) {
cout << "NO" << endl;
}
return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
// 定义四个方向:右、下、上、左
const int DIRECTIONS[4][2] = {{0,1}, {1,0}, {-1,0}, {0,-1}};
bool isFind = false; // 全局标记,表示是否已找到目标单词
// 回溯函数
// 参数说明:
// grid —— 字符网格
// N, M —— 网格行列数
// checkList —— 访问标记数组,避免重复访问
// x, y —— 当前搜索位置
// word —— 要匹配的单词
// wordIdx —— 当前已匹配到的下标
void backtracking(char grid[105][105], int N, int M, bool checkList[105][105], int x, int y, char* word, int wordIdx) {
// 若已匹配到最后一个字符,说明单词匹配成功
if (wordIdx == (int)strlen(word) - 1) {
isFind = true;
return;
}
// 向四个方向扩展
for (int d = 0; d < 4; d++) {
int nx = x + DIRECTIONS[d][0];
int ny = y + DIRECTIONS[d][1];
// 判断是否越界 + 是否未访问 + 下一个字符是否匹配
if (nx >= 0 && nx < N && ny >= 0 && ny < M &&
!checkList[nx][ny] && grid[nx][ny] == word[wordIdx + 1]) {
checkList[nx][ny] = true;
backtracking(grid, N, M, checkList, nx, ny, word, wordIdx + 1);
checkList[nx][ny] = false; // 回溯
}
}
}
int main() {
int N, M;
scanf("%d %d", &N, &M);
char word[105];
scanf("%s", word);
// 定义网格
char grid[105][105];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
scanf(" %c", &grid[i][j]); // 注意前面加空格,避免读入换行符
}
}
// 定义访问标记数组
bool checkList[105][105] = {false};
// 从每个可能的起点开始回溯搜索
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (grid[i][j] == word[0]) {
checkList[i][j] = true;
backtracking(grid, N, M, checkList, i, j, word, 0);
checkList[i][j] = false;
if (isFind) {
printf("%d %d\n", i + 1, j + 1); // 输出 1-based 坐标
return 0;
}
}
}
}
if (!isFind) {
printf("NO\n");
}
return 0;
}
Node JavaScript
// 在 N×M 的字符网格中按“上下左右”寻找目标单词;
// 找到则输出起点(1-based)坐标,否则输出 "NO"。
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const lines = [];
rl.on('line', (line) => {
lines.push(line);
});
rl.on('close', () => {
// 去除可能的 \r
for (let i = 0; i < lines.length; i++) lines[i] = lines[i].replace(/\r/g, '');
let idx = 0;
// 读取 N M
while (idx < lines.length && lines[idx].trim() === '') idx++;
if (idx >= lines.length) { console.log('NO'); return; }
const first = lines[idx++].trim().split(/\s+/);
if (first.length < 2) { console.log('NO'); return; }
const N = parseInt(first[0], 10);
const M = parseInt(first[1], 10);
if (!Number.isInteger(N) || !Number.isInteger(M) || N <= 0 || M <= 0) {
console.log('NO'); return;
}
// 读取单词(整行)
while (idx < lines.length && lines[idx].trim() === '') idx++;
if (idx >= lines.length) { console.log('NO'); return; }
const word = lines[idx++].trim();
if (word.length === 0) { console.log('NO'); return; }
// 读取网格 N 行
const grid = new Array(N);
for (let i = 0; i < N; i++) {
while (idx < lines.length && lines[idx].trim() === '') idx++;
if (idx >= lines.length) { console.log('NO'); return; }
const row = lines[idx++]; // 保留整行
if (row.length < M) { console.log('NO'); return; } // 防御:行过短
grid[i] = row.slice(0, M).split(''); // 逐字符
}
// 四方向:右、下、上、左
const DIR = [[0, 1], [1, 0], [-1, 0], [0, -1]];
let isFind = false;
// 访问标记
const check = Array.from({ length: N }, () => Array(M).fill(false));
// 回溯搜索
function dfs(x, y, wi) {
// 已匹配到最后一个字符
if (wi === word.length - 1) { isFind = true; return; }
for (const [dx, dy] of DIR) {
if (isFind) return; // 已找到就提前结束
const nx = x + dx, ny = y + dy;
if (nx >= 0 && nx < N && ny >= 0 && ny < M &&
!check[nx][ny] && grid[nx][ny] === word[wi + 1]) {
check[nx][ny] = true;
dfs(nx, ny, wi + 1);
check[nx][ny] = false; // 回溯
}
}
}
// 从每个可能的起点触发搜索
let printed = false;
search:
for (let i = 0; i < N; i++) {
for (let j = 0; j < M; j++) {
if (grid[i][j] === (word[0] || '')) {
check[i][j] = true;
dfs(i, j, 0);
check[i][j] = false;
if (isFind) {
console.log(`${i + 1} ${j + 1}`); // 1-based 坐标
printed = true;
break search;
}
}
}
}
if (!printed) console.log('NO');
});
Go
package main
import (
"bufio"
"fmt"
"os"
)
var (
// 方向:右、下、上、左
DIRECTIONS = [][2]int{{0, 1}, {1, 0}, {-1, 0}, {0, -1}}
isFind bool // 全局标记:是否已找到
)
func backtracking(grid [][]rune, N, M int, checkList [][]bool, x, y int, word []rune, idx int) {
// 若已匹配到最后一个字符,则说明成功
if idx == len(word)-1 {
isFind = true
return
}
for _, d := range DIRECTIONS {
if isFind { // 已找到则尽快返回
return
}
nx := x + d[0]
ny := y + d[1]
// 边界、未访问、字符匹配
if nx >= 0 && nx < N && ny >= 0 && ny < M &&
!checkList[nx][ny] && grid[nx][ny] == word[idx+1] {
checkList[nx][ny] = true
backtracking(grid, N, M, checkList, nx, ny, word, idx+1)
checkList[nx][ny] = false // 回溯
}
}
}
func main() {
in := bufio.NewReader(os.Stdin)
var N, M int
fmt.Fscan(in, &N, &M)
var wordStr string
fmt.Fscan(in, &wordStr)
word := []rune(wordStr)
// 读取网格
grid := make([][]rune, N)
for i := 0; i < N; i++ {
var row string
fmt.Fscan(in, &row)
grid[i] = []rune(row)
}
// 访问标记
checkList := make([][]bool, N)
for i := 0; i < N; i++ {
checkList[i] = make([]bool, M)
}
// 从每个可能的起点启动回溯
for i := 0; i < N && !isFind; i++ {
for j := 0; j < M && !isFind; j++ {
if grid[i][j] == word[0] {
checkList[i][j] = true
backtracking(grid, N, M, checkList, i, j, word, 0)
checkList[i][j] = false
if isFind {
// 输出 1-based 坐标
fmt.Printf("%d %d\n", i+1, j+1)
return
}
}
}
}
// 未找到
fmt.Println("NO")
}
时空复杂度
时间复杂度:O(NM3^L)。其中L为单词word的长度,这是一个比较宽松的上界,回溯过程中每一个点都最多有三个分支可以进入。
空间复杂度:O(NM)。check_list所占空间。
华为OD算法/大厂面试高频题算法练习冲刺训练
华子OD算法/大厂面试高频题算法冲刺训练目前开始常态化报名!目前已服务1000+同学成功上岸!
课程讲师为全网200w+粉丝编程博主@吴师兄学算法 以及小红书头部编程博主@闭着眼睛学数理化
90+天陪伴式学习,100+直播课时,300+动画图解视频,500+LeetCode经典题,500+华为OD真题/大厂真题,还有简历修改、模拟面试、陪伴小群、资深HR对接将为你解锁
可上全网独家的欧弟OJ系统练习华子OD、大厂真题
可查看链接OD真题汇总(持续更新)
绿色聊天软件戳
od1441或了解更多

浙公网安备 33010602011771号