Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- )
- /*
- Given a grid. Find maximum number of connected colors
- */
- type Cell struct {
- X int32
- Y int32
- Color int32
- }
- type Square struct {
- Color int32
- Area map[string]*Cell
- }
- func (s *Square) Merge(another *Square) {
- for k, v := range another.Area {
- s.Area[k] = v
- }
- }
- func (s *Square) Add(cell *Cell) {
- s.Area[cell.Key()] = cell
- }
- func (c Cell) Key() string {
- return fmt.Sprintf("%d%d", c.X, c.Y)
- }
- var input = [][]Cell{
- {Cell{0, 0, 0}, Cell{0, 1, 0}, Cell{0, 2, 1}, Cell{0, 3, 0},},
- {Cell{1, 0, 0}, Cell{1, 1, 2}, Cell{1, 2, 1}, Cell{1, 3, 2},},
- {Cell{2, 0, 1}, Cell{2, 1, 2}, Cell{2, 2, 2}, Cell{2, 3, 2},},
- }
- func main() {
- var squares = make(map[string]*Square)
- var maxSquare = &Square{}
- fmt.Println("Input:")
- for i, raw := range input {
- for j, cell := range raw {
- fmt.Printf("%d ", cell.Color)
- if i-1 >= 0 {
- check(cell, &input[i-1][j], squares, maxSquare)
- }
- if j-1 >= 0 {
- check(cell, &input[i][j-1], squares, maxSquare)
- }
- if i+1 < len(input) {
- check(cell, &input[i+1][j], squares, maxSquare)
- }
- if j+1 < len(raw) {
- check(cell, &input[i][j+1], squares, maxSquare)
- }
- }
- fmt.Println()
- }
- fmt.Printf("Biggest area size: %d cells\ncolor: %d\n", len(maxSquare.Area), maxSquare.Color)
- fmt.Println("Cells:")
- for _, value := range maxSquare.Area {
- fmt.Printf("x=%d y=%d\n", value.X, value.Y)
- }
- }
- func check(cell Cell, neighbourCell *Cell, squares map[string]*Square, maxSquare *Square) {
- currentSquare, currentIsInSquare := squares[cell.Key()]
- neighbourSquare, neighbourIsInSquare := squares[neighbourCell.Key()]
- //init square with current cell
- if !currentIsInSquare {
- currentArea := map[string]*Cell{cell.Key(): &cell}
- currentSquare = &Square{
- Color: cell.Color,
- Area: currentArea,
- }
- squares[cell.Key()] = currentSquare
- }
- //main logic
- if neighbourIsInSquare && currentSquare != neighbourSquare && currentSquare.Color == neighbourSquare.Color {
- currentSquare.Merge(neighbourSquare)
- squares[neighbourCell.Key()] = currentSquare
- } else if !neighbourIsInSquare && currentSquare.Color == neighbourCell.Color {
- currentSquare.Add(neighbourCell)
- squares[neighbourCell.Key()] = currentSquare
- }
- //find biggest square
- if len(maxSquare.Area) < len(currentSquare.Area) {
- maxSquare.Area = currentSquare.Area
- maxSquare.Color = currentSquare.Color
- }
- }
Add Comment
Please, Sign In to add comment