剑指offer-矩阵中的路径
来源:互联网 发布:西安理工大学知行 编辑:程序博客网 时间:2024/05/20 15:39
问题
题目:[剑指offer-矩阵中的路径]
思路
dfs+剪枝,也就是所谓的backtracking.
实现的时候有一个技巧就是,只有确实某个(i,j)出现在路径中,visited[i][j]才会被值true。
然后,失败返回后重置为false。因为不能影响这次枚举其他枚举点的状态。比如: b->c->e->c这个路径是正确的。但是如果你直接b->c->f这个路径就错误。但是,由于还是是从b开始的局面,此时这条路径失效之后,不能影响其他分支的判断,在b开始局面其他分支的判断。
b c
c e
f
需要注意的是,每次开始一个新局面应该是重置,但是,本次局面不同子局面之间的dfs应该互不影响。
代码
class Solution {public: bool hasPath(char* matrix, int rows, int cols, char* str) { vector<vector<int>> visited( rows, vector<int>(cols, 0) ); int n = strlen( str ); for( int i = 0; i < rows; ++i ){ for( int j = 0; j < cols; ++j ){ bool ret = dfs( matrix, rows, cols, i, j, visited, str, 0, n ); if(ret) return true; } } return false; }private: bool dfs( char*matrix, int rows, int cols, int i, int j, vector<vector<int>>& visited, char* str, int cur, int n ){ if( cur == n ) return true; else{ if( i < 0 || i == rows || j < 0 || j == cols ) return false; if( visited[i][j] ) return false; if( str[cur] != matrix[i*cols + j] ) return false; visited[i][j] = true; bool ret = dfs(matrix, rows, cols, i-1, j, visited, str, cur+1, n); if( ret ) return true; ret = dfs(matrix, rows, cols, i+1, j, visited, str, cur+1, n); if( ret ) return true; ret = dfs(matrix, rows, cols, i, j-1, visited, str, cur+1, n); if(ret) return true; ret = dfs(matrix, rows, cols, i, j+1, visited, str, cur+1, n); if(ret) return true; visited[i][j] = false;// 一般dfs是不清除状态的,但是这个题目必须要清除状态 return false; } }};
阅读全文
0 0
- 剑指offer--矩阵中的路径
- 《剑指offer》矩阵中的路径
- 剑指offer:矩阵中的路径
- [剑指offer]矩阵中的路径
- 剑指offer-矩阵中的路径
- 剑指offer 矩阵中的路径
- 剑指offer-矩阵中的路径
- 剑指offer-矩阵中的路径
- 剑指offer 矩阵中的路径
- [剑指offer]矩阵中的路径
- 剑指offer 矩阵中的路径
- 剑指offer --- 矩阵中的路径
- 剑指offer 66-矩阵中的路径
- 剑指offer—矩阵中的路径
- 《剑指offer》——矩阵中的路径
- 剑指offer 65 矩阵中的路径
- 剑指offer(六十五)之矩阵中的路径
- 剑指offer——矩阵中的路径
- 教你打造绚丽多彩的TextView
- 程序员快来看!经典代码替你省去多少时间?
- dubbo中几种protocol的理解
- Android获取滑动阈值(系统认为最低的滑动距离)
- having和where的区别
- 剑指offer-矩阵中的路径
- 第一个jquery插件(jquery插件)
- selenium自动化测试
- openjudge1807正方形题解
- 【SignalR学习系列】4. SignalR广播程序
- 利用tcpprobe思想和tracepoint利器可以做一个检测丢包工具
- 中点的规律
- AVL_WORKSPACE_SUITE_
- Access denied for user 'root'@'localhost' (using password:YES) 解决方法