codevs1049
来源:互联网 发布:微信小号矩阵 编辑:程序博客网 时间:2024/05/16 07:25
题目地址:http://codevs.cn/problem/1049/
分析:
只要判断其是否连通就行了,找到连通的最少步数。
代码:
#include <stdio.h>
#include <string.h>
#include <set>
#include <iostream>
using namespace std;
typedef int State[5][5];
State map,sta[500005],visit;
int sub[25][2];
int step[500005],nextx[4] = { 1, 0, -1, 0 }, nexty[4] = { 0, 1, 0, -1 };
set<string> vis;
int check ( State t )
{
char str[50];
int count = 0;
for ( int i = 0; i < 5; i ++ )
for ( int j = 0; j < 5; j ++ )
str[count++] = ( t[i][j]+'0' );
str[count] = '\0';
if ( vis.count ( str ) )
return 0;
vis.insert ( str );
return 1;
}
void dfs ( State t, int x, int y )
{
if ( x < 0 || x >= 5 || y < 0 || y >= 5 || visit[x][y] == 1 || t[x][y] == 0 )
return ;
visit[x][y] = 1;
for ( int i = 0; i < 4; i ++ )
dfs ( t, x+nextx[i], y+nexty[i] );
}
void print ( State t )
{
int i,j;
for ( i = 0; i < 5; i ++ )
{
for ( j = 0; j < 5; j ++ )
printf ( "%d ", t[i][j] );
printf ( "\n" );
}
printf ( "\n" );
}
int is_ok ( State t )
{
int i;
memset ( visit, 0, sizeof ( visit ) );
for ( i = 0; i < 25; i ++ )
if ( t[i/5][i%5] )
break ;
dfs ( t, i/5, i%5 );
for ( i = 0; i < 25; i ++ )
if ( visit[i/5][i%5] == 0 && t[i/5][i%5] == 1 )
return 0;
return 1;
}
int bfs ( )
{
int front,rear,i,j,count;
vis.clear ( );
front = 0;
rear = 1;
memcpy ( sta[front], map, sizeof ( map ) );
step[front] = 0;
while ( front < rear )
{
count = 0;
if ( is_ok ( sta[front] ) )
return step[front];
for ( i = 0; i < 5; i ++ )
for ( j = 0; j < 5; j ++ )
if ( sta[front][i][j] )
{
sub[count][0] = i;
sub[count][1] = j;
count ++;
}
for ( i = 0; i < count; i ++ )
for ( j = 0; j < 4; j ++ )
{
int nx = sub[i][0]+nextx[j];
int ny = sub[i][1]+nexty[j];
if ( nx < 0 || nx >= 5 || ny < 0 || ny >= 5 || sta[front][nx][ny] )
continue ;
memcpy ( sta[rear], sta[front], sizeof ( sta[front] ) );
sta[rear][nx][ny] = 1;
if ( check ( sta[rear] ) )
{
step[rear] = step[front]+1;
rear ++;
}
}
front ++;
}
return -1;
}
int main ( )
{
int i,j;
char str[10];
for ( i = 0; i < 5; i ++ )
{
scanf ( "%s", str );
for ( j = 0; j < 5; j ++ )
map[i][j] = str[j]-'0';
}
printf ( "%d", bfs ( ) );
return 0;
}
- codevs1049
- 【日常学习】【迭代加深搜索】codevs1049 棋盘染色题解
- 2.5.2 控制飞船移动
- Machine Learning Foundations 第13节-第16节
- android内存泄露优化总结
- 深入理解HTTP Session(2)
- poj 2139 Floyd-Warshall算法求最短路
- codevs1049
- AsyncTask的学习
- DevComponents.DotNetBar2显示控件的方法
- Hibernate注解法一对多时,赖加载问题
- 设计模式笔记——简单工厂模式
- 招聘管理
- animation几个比较好玩的属性(alternate,及animation-fill-mode)
- 大数据之简介
- Rails中的使用者验证:Devise