标签:row 剑指offer false ret logs subject matrix 第一个 code
【思路】dfs尝试从每个结点开始走,走过一个结点就将其值置为‘\0‘,走完之后记录是否成功,并将值恢复。
1 class Solution { 2 public: 3 bool dfs(char* matrix, int rows, int cols, char* str, int i, int j){ 4 if(str == NULL || *str == ‘\0‘){ 5 return true; 6 } 7 bool ans = false; 8 if((i>= 0) && (i < rows) && (j >= 0) && (j < cols) && (matrix[i * cols + j] == *str)){ 9 matrix[i * cols + j] = ‘\0‘; 10 ans = dfs(matrix, rows, cols, str + 1, i - 1, j) 11 ||dfs(matrix, rows, cols, str + 1, i + 1, j) 12 ||dfs(matrix, rows, cols, str + 1, i, j - 1) 13 ||dfs(matrix, rows, cols, str + 1, i, j + 1); 14 matrix[i * cols + j] = *str; 15 } 16 return ans; 17 } 18 bool hasPath(char* matrix, int rows, int cols, char* str) 19 { 20 for(int i = 0;i < rows;i ++){ 21 for(int j = 0;j < cols;j ++){ 22 if(dfs(matrix, rows, cols, str, i, j)){ 23 return true; 24 } 25 } 26 } 27 return false; 28 } 29 };
标签:row 剑指offer false ret logs subject matrix 第一个 code
原文地址:http://www.cnblogs.com/lca1826/p/6588956.html