POJ 1979 Red and Black 解题报告

《程序设计导引及在线实践》上面有这道题,练习了递归的思想。

 

#include <stdio.h> const int MAX_BRICK_SIZE = 20; /*用来存储方块符号信息*/ char bricks[MAX_BRICK_SIZE + 1][MAX_BRICK_SIZE + 1]; int W, H; /*递归调用的函数。 *假设以(i, j)为起点,则总的可以经过的黑瓷砖数为: * 1 + countBricks(i-1,j) + countBricks(i+1,j) * + countBricks(i,j-1) + countBricks(i,j+1) * (上下左右各算一次) */ int countBricks(int i, int j) { /*注意,i与行数H比较,j与列数W比较*/ if(i < 0 || i >= H || j < 0 || j >= W) return 0; if(bricks[i][j] == '#') return 0; /*别忘了置当前位置为'#',表示已经经过了*/ bricks[i][j] = '#'; return 1 + countBricks(i-1,j) + countBricks(i+1,j) + countBricks(i,j-1) + countBricks(i,j+1); } int main() { while(scanf("%d%d", &W, &H), !(W == 0 && H == 0)) { for(int i = 0; i < H; ++i) scanf("%s", bricks[i]); for(int i = 0; i < H; ++i) for(int j = 0; j < W; ++j) if(bricks[i][j] == '@') printf("%d/n", countBricks(i, j)); } return 0; }

你可能感兴趣的:(存储)