1. 程式人生 > >nyoj 499迷宮【DFS】

nyoj 499迷宮【DFS】

神獸題:【DFS】

# include <stdio.h>
# include <string.h>
# define M 20

int book[M][M];
int r, c;
int count;
int map[M][M];

void dfs(int x, int y);

int main(void)
{
	int n;
	scanf("%d", &n);
	while (n--)
	{
		count = 0;
		memset(book, 0, sizeof(book));
		scanf("%d %d", &r, &c);
		int i, j;
		for (i = 0; i < r; i++)
		{
			for (j = 0; j < c; j++)
			{
				scanf("%d", &map[i][j]);
			}
		}
		dfs(0, 0);
		printf("%d\n", count);
	}
	return 0;
}

void dfs(int x, int y)
{
	if ((x < 0 || y < 0 || x >= r || y >= c) || book[x][y] == 1 || map[x][y] == 1)//不成功的條件要放在前面
	{
		return ;
	}
	if (x == (r-1) && y == (c-1))//成功的條件
	{
		count ++;
		return ;
	}		
	book[x][y] = 1;
	dfs(x, y+1);
	dfs(x+1, y);
	dfs(x, y-1);
	dfs(x-1, y);
	book[x][y] = 0;
}