最近在学习图论算法,其实已经学了很久了,发现自己没什么进步,究其原因,是自己平时写代码的时间还是太少了,现在,我就开始将自己的学到的东西慢慢的用来解决一些题目,同时也帮助自己更还的理解算法的本质东西!加油!
在 zoj中我找到了一些题目来了练手,同时把东西写出来!
下面是题目!
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Input
The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.
- '.' - a black tile
- '#' - a red tile
- '@' - a man on a black tile(appears exactly once in a data set)
Output
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
Sample Input
Sample Input
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
........... 11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
Sample Output
45
59
6
13
下面是我用dfs搜索来写的代码!
char map[21][21];
int m,n;
int count;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//表示移动的方向,可以利用这个数组来表示
int dfs(int x,int y)
{
int i,xx,yy;
map[x][y]='#';
for(i=0;i<4;i++)
{
xx=x+dir[i][0];
yy=y+dir[i][1];
if(xx<0||yy<0||xx>=m||yy>=n)
continue;
if(map[xx][yy]=='.')
{
map[xx][yy]='#';
count++;
//printf("%d",count);
dfs( xx, yy);
}
}
return count;
}
int main()
{
while(1)
{
int i,j,x,y;
scanf("%d%d",&n,&m);
if(m==0&&n==0)
break;
char temp;
scanf("%c",&temp);//当前面已经输入了数字,后面有要输入字符时,因为数字输入后要按下enter键,而enter呢又是一个字符,所以应该将其吸收,这时可以用这个办法!
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='@')
{
x=i;
y=j;
}
}
scanf("%c",&temp);
}
count=0;
dfs(x,y);
printf("%d\n",count+1); //因为@也算一个黑砖所以count要加一!
}
}
这是用dfs来计算一个迷宫里面砖的个数,我现在只能想到用dfs来进行搜索,其实dfs的使用很简单,但是不是很好理解,现在将其归纳一下!
当图的存储是用邻接矩阵来存储时,
dfs (顶点i)
{ visited[i]=1;
for (j=0;j<n;j++)//对其他所有的顶点j
{
if(edge[i][j]==1&&visted[j])//顶点j没有访问过,j是i的邻接顶点!
{
//递归搜索前的准备在这写代码
dfs (顶点j)
//以下是回退的位置,但需要回退恢复原来的情况时要在这个地方写代码!
}
}
}
若是利用邻接表来存储图时
dfs(顶点i)
{ vistited[i]=1;
//p是i的表头指针;
while(p!=nuLL)
{
if(visit[j]!=1)
{
dfs(j);
}
}
}
这是一些比较概要的东西在实际的过程中还是要多加体会!