首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

poj 1321搜索的有关问题(DFS,回溯)

2012-09-20 
poj 1321搜索的问题(DFS,回溯)#includeiostreamusing namespace stdconst int Max 10bool board[Max

poj 1321搜索的问题(DFS,回溯)

#include<iostream>using namespace std;const int Max = 10;bool board[Max][Max], row[Max], col[Max]; // row[i],col[j]分别记录第i行,第j列被访问了没有。int len, num, ans;void dfs(int depth, int start_line){ if(depth == num){ ans ++; return; } for(int i = start_line + 1; i <= len; i ++) for(int j = 1; j <= len; j ++) if(board[i][j] == true && row[i] == false && col[j] == false){ row[i] = true; col[j] = true; dfs(depth + 1, i); row[i] = false; col[j] = false; }}int main(){ int i, j; char c; while(1){ cin >> len >> num; if(len == -1 && num == -1) break; memset(board, false, sizeof(board)); for(i = 1; i <= len; i ++) for(j = 1; j <= len; j ++){ cin >> c; if(c == '#') board[i][j] = true; }ans = 0;memset(row, false, sizeof(row));memset(col, false, sizeof(col));int start_line = len - num + 1; // 第一颗棋子的位置可能在 1 ~ start_line 行之间。for(i = 1; i <= start_line; i ++)for(j = 1; j <= len; j ++)if(board[i][j] == true){row[i] = true; col[j] = true;dfs(1, i);row[i] = false; col[j] = false;}cout << ans << endl;}return 0;}?关于代码中的回溯问题,现在说实在的不能理解啊~!真的想了好久,还是不懂!要向别人去请教一下才能懂!!

热点排行