剑指offer--面试题12:矩阵中的路径
来源:互联网 发布:python重定向到文件 编辑:程序博客网 时间:2024/06/07 00:54
#include <stdio.h>#include <string.h>bool hasPathCore( char* A, int rows, int cols, int row, int col, char* str, int& pathLen, bool* visited);bool hasPath(char* A, int rows, int cols, char* str){ if(A == NULL || rows < 1 || cols < 1 || str == NULL) return false; bool *visited = new bool[rows * cols]; memset(visited, 0, rows * cols); int pathLen = 0; for(int row = 0; row < rows; ++row) for(int col = 0; col < cols; ++col) if(hasPathCore(A, rows, cols, row, col, str,pathLen, visited)) return true; delete[] visited; return false;}bool hasPathCore( char* A, int rows, int cols, int row, int col, char* str, int& pathLen, bool* visited){ if(str[pathLen] == '\0') return true; bool hasPath = false; if(row >= 0 && row < rows && col >= 0 && col < cols && A[row * cols + col] == str[pathLen]&&!visited[row * cols + col]) { ++pathLen; visited[row * cols + col] = true; hasPath = hasPathCore(A, rows, cols, row, col - 1, str, pathLen, visited) || hasPathCore(A, rows, cols, row, col + 1, str, pathLen, visited) || hasPathCore(A, rows, cols, row - 1, col, str, pathLen, visited) || hasPathCore(A, rows, cols, row + 1, col, str, pathLen, visited); if(!hasPath) { --pathLen; visited[row * cols + col] = false; } } return hasPath;}int main(){char A[3][4]={'a','b','t','g','c','f','c','s','j','d','e','h'};for(int i=0;i<3;++i){for(int j=0;j<4;++j)printf("%c ",A[i][j]);printf("\n");}char *string="bfce";char *String="abfb";if(hasPath((char *)A, 3, 4, string))printf("\n矩阵中存在路径:%s!\n",string);elseprintf("矩阵中不存此路径%s,或异常退出!\n",string);if(hasPath((char *)A, 3, 4, String))printf("\n矩阵中存在路径:%s!\n",String);elseprintf("矩阵中不存在路径:%s,或异常退出!\n",String); return 0;}
阅读全文
0 0
- 剑指offer--面试题12:矩阵中的路径
- 【剑指offer】面试题12:矩阵中的路径
- 《剑指Offer》学习笔记--面试题66:矩阵中的路径
- 【剑指Offer学习】【面试题66:矩阵中的路径】
- 《剑指offer》面试题66 矩阵中的路径
- 剑指offer--面试题66:矩阵中的路径
- 剑指Offer面试题66:矩阵中的路径 java实现
- 剑指offer-面试题66-矩阵中的路径
- 【剑指Offer】面试题66:矩阵中的路径
- 剑指offer面试题12:矩阵中的路径Java实现版
- 剑指offer--矩阵中的路径
- 《剑指offer》矩阵中的路径
- 剑指offer:矩阵中的路径
- [剑指offer]矩阵中的路径
- 剑指offer-矩阵中的路径
- 剑指offer 矩阵中的路径
- 剑指offer-矩阵中的路径
- 剑指offer-矩阵中的路径
- 程序员对谷歌、百度正确的使用方法
- 分割句子
- Struts + Spring +ibatis 整合开发步骤
- 使用intelliJ IDEA 2017 for mac 编写jsp文件且在java文件中链接MySQL数据库的问题
- Android Kotlin
- 剑指offer--面试题12:矩阵中的路径
- 中兴新支点Linux桌面操作系统初次使用体验
- 基于深度学习的验证码自动识别(caffe)
- [LeetCode] 566. Reshape the Matrix
- 20170711考试总结
- Redis-Bitmaps应用
- MSB与LSB
- android倒计时获取验证码按钮
- 字符串——判断一个括号字符串是否匹配