UVA 639 - Don't Get Rooked

本文介绍了一种利用回溯法解决迷宫问题的算法实现,详细阐述了算法的实现过程,并提供了代码示例。

连接是:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=580

AC了。依旧是回溯法。跟生成binary的array的所有情况是差不多的implementation。

View Code
 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 
 5 const int MAXGRID = 4;
 6 char grid[MAXGRID][MAXGRID];
 7 int vis[MAXGRID][MAXGRID];
 8 int lines;
 9 
10 bool isRowValid(int row, int col){
11     if (grid[row][col] == 'X')
12         return false;
13     for (int j = col-1; j >= 0; j--){
14         if (vis[row][j])
15             return false;
16         else if (grid[row][j] == 'X')
17             return true;
18     }
19     return true;
20 }
21 
22 bool isColValid(int row, int col){
23     if (grid[row][col] == 'X')
24         return false;
25     for (int i = row-1; i >= 0; i--){
26         if (vis[i][col])
27             return false;
28         else if (grid[i][col] == 'X')
29             return true;
30     }
31     return true;
32 }
33 
34 void search(int& max, int temp_max, int row, int col){
35     if (lines == col){
36         if (max < temp_max)
37             max = temp_max;
38         // cout << endl;
39     }
40     else{
41         // cout << "(" << row << "," << col << ")" << " ";
42         int new_row = row+1, new_col = col;
43         if (new_row == lines){
44             new_row = 0;
45             new_col++;
46         }
47         if (isRowValid(row,col) && isColValid(row,col)){
48             vis[row][col] = 1;
49             search(max, temp_max+1, new_row, new_col);
50         }
51         vis[row][col] = 0;
52         search(max, temp_max, new_row, new_col);
53     }
54 }
55 
56 int main(int argc, char *argv[]){
57     while (cin >> lines && lines){
58         for (int row = 0; row < lines; row++){
59             cin >> grid[row];
60         }
61         // memset(vis, 0, sizeof(vis));
62         for (int i = 0; i < lines; i++){
63             for (int j = 0; j < lines; j++){
64                 vis[i][j] = 0;
65             }
66         }
67 
68         int max = 0;
69 
70         search(max, 0, 0, 0);
71         cout << max << endl;
72     }
73     return 0;
74 }

 

转载于:https://www.cnblogs.com/frankdj412/archive/2013/02/07/2908715.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值