标签:
回溯解法,和博客上其他同学大同小异。
不同的是我给城市围了一圈墙,减少了个范围判断。
#include <iostream> #include <memory.h> using namespace std; char board[6][6]; //为4*4的城市围一圈墙,方便判断 int n; int maxCount; bool Shoot(int x, int y, int dx, int dy) //x,y为射击原点;dx,dy为射击方向向量,打到堡垒返回false { int x1 = x, y1 = y; do { x1 += dx; y1 += dy; if (board[x1][y1] == ‘o‘) //打到堡垒了 return false; } while (board[x1][y1] != ‘X‘); //一直打到墙 return true; } bool CanPut(int x, int y) { if (board[x][y] == ‘.‘ && //四面各开一枪如果都没打上堡垒 Shoot(x, y, 0, 1) && Shoot(x, y, 0, -1) && Shoot(x, y, 1, 0) && Shoot(x, y, -1, 0)) return true; return false; } void Slove(int k, int count) { if (k == n*n) maxCount = count > maxCount ? count : maxCount; else { int x = k % n + 1; int y = k / n + 1; if(CanPut(x, y)) { board[x][y] = ‘o‘; Slove(k+1, count+1); //进入分支 board[x][y] = ‘.‘; //回溯 } Slove(k+1, count); } } int main() { while (cin >> n && n) { memset(board, ‘X‘, sizeof(board)); //载入地图 for (int x = 1; x < n + 1; ++x) for (int y = 1; y < n + 1; ++y) cin >> board[x][y]; maxCount = 0; Slove(0, 0); cout << maxCount <<endl; } }
标签:
原文地址:http://www.cnblogs.com/wangzexi/p/4736321.html