@jtahstu
2017-09-15T02:07:41.000000Z
字数 1354
阅读 3108
算法
时间限制:3000 ms | 内存限制:65535 KB
难度:4
南阳理工学院校园里有一些小河和一些湖泊,现在,我们把它们通一看成水池,假设有一张我们学校的某处的地图,这个地图上仅标识了此处是否是水池,现在,你的任务来了,请用计算机算出该地图中共有几个水池。
第一行输入一个整数N,表示共有N组测试数据
每一组数据都是先输入该地图的行数m(0 < m < 100)与列数n(0 < n < 100),然后,输入接下来的m行每行输入n个数,表示此处有水还是没水(1表示此处是水池,0表示此处是地面)
输出该地图中水池的个数。
要注意,每个水池的旁边(上下左右四个位置)如果还是水池的话的话,它们可以看做是同一个水池。
2
3 4
1 0 0 0
0 0 1 1
1 1 1 0
5 5
1 1 1 1 0
0 0 1 0 1
0 0 0 0 0
1 1 1 0 0
0 0 1 1 1
2
3
走过的标0,然后深搜
# author: jtusta# contact: root@jtahstu.com# site: http://www.jtahstu.com# software: RubyMine# time: 2017/6/9 22:08class PollsNumdef initialize@a = []@n = 0@m = 0@count = 0enddef inputt = gets.stripfor x in 1..t.to_i# 初始化一下@a = []@count = 0# 输入一个二维数组l = gets.strip.split(/\s+/)@n = l[0].to_i@m = l[1].to_ifor i in 1..@nline = gets.split(/\s+/)@a[i] = []for j in 1..@m@a[i][j] = line[j-1].to_iendend# solveself.solveendend# 深搜def dfs(i,j)if i-1>0 && @a[i-1][j]==1@a[i-1][j]=0self.dfs(i-1,j)endif i<@n && @a[i+1][j]==1 # 右@a[i+1][j]=0self.dfs(i+1,j)endif j-1>0 && @a[i][j-1]==1 # 上@a[i][j-1]=0self.dfs(i,j-1)endif j<@m && @a[i][j+1]==1 # 下@a[i][j+1]=0self.dfs(i,j+1)endenddef solvefor i in 1..@nfor j in 1..@mif @a[i][j]==1@count += 1@a[i][j]=0self.dfs(i,j)endendendp @countendendpolls = PollsNum.newpolls.input
输出
/usr/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Users/jtusta/Documents/Code/Ruby/algorithm/polls_num.rb23 41 0 0 00 0 1 11 1 1 025 51 1 1 1 00 0 1 0 10 0 0 0 01 1 1 0 00 0 1 1 13Process finished with exit code 0