dfs C++代码
矩阵中的路径
http://www.nowcoder.com/questionTerminal/2a49359695a544b8939c77358d29b7e6
class Solution { public: int flag = 0; //标记是否成功搜索到word int map[205][205]; //标记是否进入过该格子 int rows, columns; int moverow[4] = {0, 0, -1, 1}; int movecol[4] = {1, -1, 0, 0}; //四个移动方向 bool hasPath(vector<vector<char> >& matrix, string word) { rows = (int) matrix.size(); columns = (int) matrix[0].size(); memset(map, 0, sizeof(map)); for(int i = 0; i < rows; i ++) for(int j = 0; j < columns; j ++) dfs(matrix, 0, word, i, j); if(flag) return 1; else return 0; } void dfs(vector<vector<char> >& matrix, int lnow, string word, int x, int y) { if(flag == 1) return; if(lnow == word.length()) { flag = 1; return; } if(x < 0 || y < 0 || x >= rows || y >= columns || matrix[x][y] != word[lnow] || map[x][y] != 0) return; map[x][y] = 1; //当前格子已搜索过 lnow ++; //当前格子里字母符合查找需要 for(int i = 0; i < 4; i ++) { int xx = x + moverow[i], yy = y + movecol[i]; dfs(matrix, lnow, word, xx, yy); } lnow --; map[x][y] = 0; //恢复 }
};