nyoj1180Maze

題目鏈接:

http://acm.nyist.net/JudgeOnline/problem.php?pid=1180

題目大意:有個迷宮,@代表你所在位置,字符 . 表示可走,#表示不可走,問在一個地圖中能到達的 . 有多少個。
值得注意的是,也要算在內。
思路:bfs,dfs應該都可以,本人用的bfs。
AC代碼:

#include <stdio.h>
#include <string.h>
char a[21][21], b[21][21];
int n, m, next[444][2], con, step[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int bfs(int i) {
	if(i >= con) return 0;
	for(int j = 0; j < 4; j++) {
		int tx = next[i][0]+step[j][0], ty = next[i][1]+step[j][1];
		if(tx>=0&&tx<m&&ty>=0&&ty<n&&b[tx][ty]) {
			b[tx][ty] = 0;
			if(a[tx][ty]=='.') {
				next[con][0] = tx;
				next[con++][1] = ty;
			}
		}
	}
	int p = 1+bfs(i+1);
	return p;
}
int main() {
	int i, j;
	while(~scanf("%d%d", &n, &m)) {
		if(n==0&&m==0) break;
		memset(b, 1, sizeof(b));
		for(i = 0; i < m; i++) {getchar();
			for(j = 0; j < n; j++) {
				scanf("%c", &a[i][j]);
				if(a[i][j] == '@') {
					next[0][0] = i;
					next[0][1] = j;
				}
			}
		}
		con = 1;
		printf("%d\n", bfs(0));
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章