这个题很久之前做过,是N皇后问题的一个变式,之前用的是递归,前几天看数据结构,想着用栈实现看看,然后就写了一下。
大概思路是维持一个栈,和一个不断更新最大栈高的变量ans,每审查一个新元素,和栈中已经有的元素进行对比,不冲突就入栈。
当一种可能的方案运行完成后,栈顶元素出栈。跳转到另一个方案。具体代码如下:
1 #include <cstdio> 2 #include <iostream> 3 #include <cstdlib> 4 5 using namespace std; 6 7 const int N = 4; 8 char Matrix[N][N]; 9 struct Block{ 10 int x, y; 11 Block(int xx = 0, int yy = 0) : x(xx), y(yy) {}; 12 }; 13 14 bool compare(Block const p1, Block const p2){ 15 int max_x = p1.x > p2.x ? p1.x : p2.x; 16 int max_y = p1.y > p2.y ? p1.y : p2.y; 17 int min_x = p1.x < p2.x ? p1.x : p2.x; 18 int min_y = p1.y < p2.y ? p1.y : p2.y; 19 if(p1.y == p2.y){ 20 for(int i = min_x; i < max_x; i++){ 21 if(Matrix[i][p1.y] == 'X') return true; 22 } 23 }else if(p1.x == p2.x){ 24 for(int i = min_y; i < max_y; i++){ 25 if(Matrix[p1.x][i] == 'X') return true; 26 } 27 } 28 return false; 29 } 30 31 bool judge(Block const p1, Block const p2){ 32 return (p1.x == p2.x && !compare(p1, p2)) 33 || (p1.y == p2.y && !compare(p1, p2)) ; 34 } 35 36 int collectBlock(int level){ 37 int ans = -1; 38 int res_index = 0; 39 int count = 0; 40 41 Block b(0,0); 42 Block res[16]; 43 do { 44 //主要逻辑在这里 45 if(Matrix[b.x][b.y] != 'X' && b.x < level && b.y < level){ 46 for(int i = 0; i < res_index; ++i){ 47 if(judge(res[i], b)) count++; 48 } 49 if(count == 0){ 50 res[res_index++] = b; 51 } 52 b.y++; 53 }else{ 54 b.y++; 55 } 56 count = 0; 57 if(b.y >= level){ 58 b.x++; b.y = 0; 59 } 60 if(b.x >= level){ 61 ans = ans > res_index ? ans : res_index; 62 res_index--; //这个地方注意栈顶指针的指向,之前用的是res[res_index--],老是出错 63 b = res[res_index]; 64 if(res_index < 0) break; 65 b.y++; 66 } 67 } while(b.x >= 0 || b.y < level); 68 return ans; 69 } 70 71 int main(){ 72 int level; 73 while(1){ 74 cin >> level; 75 if(level == 0) break; 76 for(int i = level-1; i >= 0; --i){ 77 for(int j = 0; j < level; ++j){ 78 cin >> Matrix[i][j]; 79 } 80 } 81 int rst = collectBlock(level); 82 cout << rst << endl; 83 } 84 return 0; 85 }
浙公网安备 33010602011771号