题解 | 剪纸游戏

剪纸游戏

https://www.nowcoder.com/practice/33054daa2cc04fd6b97a0d18ccfc66a0

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	buf := bufio.NewReader(os.Stdin)
	var n, m int
	fmt.Fscan(buf, &n, &m)
	sli := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(buf, &sli[i])
	}
	addX := [4]int{0, 0, 1, -1}
	addY := [4]int{1, -1, 0, 0}
	visited := make([][]bool, n)
	for i := range visited {
		visited[i] = make([]bool, m)
	}
	type p struct {
		x, y int
	}
	total := 0
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if sli[i][j] == '.' && !visited[i][j] {
				position := []p{{i, j}}
				visited[i][j] = true
				maxX, minX := i, i
				maxY, minY := j, j
				count := 0
				for len(position) > 0 {
					c := position[0]
					position = position[1:]
					if c.x > maxX {
						maxX = c.x
					} 
                    if c.x < minX {
						minX = c.x
					}
					if c.y > maxY {
						maxY = c.y
					} 
                    if c.y < minY{
						minY = c.y
					}
					count++
					for k := 0; k < 4; k++ {
						nx, ny := c.x+addX[k], c.y+addY[k]
						if nx >= 0 && ny >= 0 && nx < n && ny < m && !visited[nx][ny] && sli[nx][ny] == '.' {
							visited[nx][ny] = true
							position = append(position, p{nx, ny})
						}
					}
				}
				if (maxX-minX+1)*(maxY-minY+1) == count {
					total++
				}
			}
		}
	}
	fmt.Print(total)
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务