当前位置: 首页 > news >正文

【力扣 中等 C】79. 单词搜索

目录

题目

解法一:回溯


题目

解法一:回溯

void swap(char* a, char* b) {char tmp = *a;*a = *b;*b = tmp;
}void reverse(char* str) {int start = 0, end = strlen(str) - 1;while (start < end) {swap(&str[start++], &str[end--]);}
}bool search(char** board, int m, int n, int i, int j,const char* word, int index) {if (word[index] == '\0') {return true;}if (i < 0 || i == m || j < 0 || j == n || word[index] != board[i][j]) {return false;}board[i][j] = '#';bool exist = search(board, m, n, i - 1, j, word, index + 1) || search(board, m, n, i + 1, j, word, index + 1) || search(board, m, n, i, j - 1, word, index + 1) || search(board, m, n, i, j + 1, word, index + 1);board[i][j] = word[index];return exist;
}bool exist(char** board, int boardSize, int* boardColSize, char* word) {const int m = boardSize, n = *boardColSize;int boardLetterCnts[128] = {0};for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {boardLetterCnts[board[i][j]]++;}}int wordLetterCnts[128] = {0};int len = strlen(word);for (int i = 0; i < len; i++) {wordLetterCnts[word[i]]++;}for (int i = 'A'; i <= 'Z'; i++) {if (boardLetterCnts[i] < wordLetterCnts[i] || boardLetterCnts[i + 32] < wordLetterCnts[i + 32]) {return false;}}char newWord[len + 1];strcpy(newWord, word);if (wordLetterCnts[word[0]] > wordLetterCnts[word[len - 1]]) {reverse(newWord);}for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (search(board, m, n, i, j, newWord, 0)) {return true;}}}return false;
}

相关文章:

  • Java基础(Maven配置)
  • 【Elasticsearch】most_fields、best_fields、cross_fields 的区别与用法
  • JVM调优实战 Day 10:性能指标采集与可视化
  • 单元测试和集成测试的区别
  • 鸿蒙 Scroll 组件深度解析:丝滑滚动交互全场景实现
  • spring中maven缺少包如何重新加载,报错java: 程序包org.springframework.web.reactive.function不存在
  • win10部署本地LLM和AI Agent
  • docker-compose部署nacos
  • 基于Uniapp+SpringBoot+Vue 的在线商城小程序
  • 前端面试专栏-主流框架:15.Vue模板编译与渲染流程
  • 给自己网站增加一个免费的AI助手,纯HTML
  • VScode使用usb转网口远程开发rk3588
  • InfluxDB 3 Core最后值缓存深度实践:毫秒级响应实时数据的核心引擎
  • 分布式电源采集控制装置:山东光伏电站的“智能中枢”
  • 典型工程应用三
  • Python pyserial库【串口通信】全面讲解
  • vue-28(服务器端渲染(SSR)简介及其优势)
  • 桌面小屏幕实战课程:DesktopScreen 16 HTTP
  • 【Go语言-Day 10】深入指针应用:解锁函数“引用传递”与内存分配的秘密
  • 进阶向:Flask框架详解,从零开始理解Web开发利器