POJ 1979 Red and Black【深度优先搜索】
2014-07-11 18:09
225 查看
题目链接:http://poj.org/problem?id=1979
题目大意:一个矩形的房间地板被分为w*h个小块,每一个小块不是红的就是黑的,你首先站在一个黑色小块上,你只能朝你的四个方向(上下左右)移动,且不能到达红色的小块上,问你最多能到达多少个小块。
很简单的dfs深度优先搜索
没搜索过一个格子,将该格子设置为红色,之后的搜索就不会再搜索到该格子,就不会造成重复,因为该题有很多数据,记得每次处理数据是初始化各数组及其他数据。
代码如下:
题目大意:一个矩形的房间地板被分为w*h个小块,每一个小块不是红的就是黑的,你首先站在一个黑色小块上,你只能朝你的四个方向(上下左右)移动,且不能到达红色的小块上,问你最多能到达多少个小块。
很简单的dfs深度优先搜索
没搜索过一个格子,将该格子设置为红色,之后的搜索就不会再搜索到该格子,就不会造成重复,因为该题有很多数据,记得每次处理数据是初始化各数组及其他数据。
代码如下:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define N 22 using namespace std; int w,h; char tile ; int ans; void bfs(int row,int column) { if(row<0||column<0||row>h||column>w) return ; else { ans++; if(tile[row+1][column]=='.') { tile[row+1][column]='#'; bfs(row+1,column); } if(tile[row-1][column]=='.') { tile[row-1][column]='#'; bfs(row-1,column); } if(tile[row][column+1]=='.') { tile[row][column+1]='#'; bfs(row,column+1); } if(tile[row][column-1]=='.') { tile[row][column-1]='#'; bfs(row,column-1); } } } int main() { scanf("%d%d",&w,&h); int row,column; while(w!=0&&h!=0) { ans=0; for(int i=0;i<h;i++) scanf("%s",tile[i]); for(int i=0;i<h;i++) for(int j=0;j<w;j++) { if(tile[i][j]=='@') { row=i; column=j; tile[i][j]='#'; } } bfs(row,column); printf("%d\n",ans); memset(tile,0,sizeof(tile)); scanf("%d%d",&w,&h); } return 0; }
相关文章推荐
- 深度优先搜索(DFS):POJ1979--Red and Black
- Red and Black (POJ 1979,深度优先搜索)
- poj1979——Red and Black
- poj 1979 , zoj 2165 Red and Black【dfs,入门题】
- poj 1979 red and black
- POJ-1979-Red and Black
- poj 1979 Red and Black
- poj 1979 zoj 2165 Red and Black 深搜做法
- POJ 1979 Red and Black
- zoj 2165 Red and Black (DFs)poj 1979
- POJ 1979 Red and Black(C语言堆栈实现)
- POJ 1979 Red and Black
- poj 1979 Red and Black
- POJ 1979 Red and Black 解题报告
- POJ_1979 Red and Black 迷宫类
- POJ 1979 Red and Black
- POJ1979 Red and Black dfs基础题
- POJ 1979 Red and Black(BFS广度优先搜索)
- zoj 2165||poj 1979 red and black (dfs)
- poj 1979 Red and Black