poj 1164(DFS)

第一次完成DFS

http://acm.pku.edu.cn/JudgeOnline/problem?id=1164

题目求: 房间的个数  和  房间的最大面积。

思路:为了调试看起来方便,用8表示墙,用0表示通路(当然房间区域也是可以走通的,所以也用0表示),用(2*row+1)*(2*column+1)的矩阵来表示(0 ≤ i ≤ 2*row ,0 ≤ j ≤ 2*column),当 i,j 都为奇数时,点(i , j)表示房间区域, 其余则为墙或门。

心得:原先没有想到还有这种情况:

3 3
3 2 6
1 0 4
9 8 12

经过调试发现,房间区域为8了,但路上还是0,这样就会引起重复计算,对dfs()做了修改:

while()里加了这句 room[i][j] == '0');
把这句  len++;   提到最前。

代码
#include<stdio.h>
#include
<string.h>

int row, column, len;
char room[101][101];

void dfs(int i, int j)
{
while(i>=1 && i<=(row<<1) && j>=1 && j<=(column<<1) && room[i][j] == '0')
{
len
++;
room[i][j]
= '8';
if(room[i][j+1] == '0')
{
room[i][j
+1] = '8';
dfs(i, j
+2);
}
if(room[i+1][j] == '0')
{
room[i
+1][j] = '8';
dfs(i
+2, j);
}
if(room[i][j-1] == '0')
{
room[i][j
-1] = '8';
dfs(i, j
-2);
}
if(room[i-1][j] == '0')
{
room[i
-1][j] = '8';
dfs(i
-2, j);
}
}
}

int main()
{
int i, j, nRoom, max, num;
while(scanf("%d %d", &row, &column) != EOF)
{
for(i=0; i<=(row<<1); i++) //初始化
for(j=0; j<=(column<<1); j++)
room[i][j]
= '8'; //8为墙,0为路

for(i=1; i<=(row<<1); i+=2) //铺房间
for(j=1; j<=(column<<1); j+=2)
{
scanf(
"%d", &num);
room[i][j]
= '0';
if(!(num&1) && room[i][j-1] == '8') room[i][j-1] = '0';
if(!(num&2) && room[i-1][j] == '8') room[i-1][j] = '0';
if(!(num&4) && room[i][j+1] == '8') room[i][j+1] = '0';
if(!(num&8) && room[i+1][j] == '8') room[i+1][j] = '0';
}

max
= 0;
nRoom
= 0;
for(i=1; i<=(row<<1); i+=2)
for(j=1; j<=(column<<1); j+=2)
if(room[i][j] == '0')
{
nRoom
++;
len
= 0;
dfs(i, j);
if(len > max) max = len;
}

printf(
"%d\n%d\n", nRoom, max);
}
return 0;
}

原文地址:https://www.cnblogs.com/submarinex/p/1941250.html