Approach
Depth-first search
For Codeforces 679C — Bear and Square Grid, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 91 lines of Go from the credited upstream file 679C.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1package main2 3import (4 . "fmt"5 "io"6)7 89func cf679C(in io.Reader, out io.Writer) {10 var n, k, ans, ts int11 Fscan(in, &n, &k)12 a := make([]string, n)13 for i := range a {14 Fscan(in, &a[i])15 }16 17 dir4 := []struct{ x, y int }{{0, -1}, {0, 1}, {-1, 0}, {1, 0}}18 id := make([][]int, n)19 for i := range id {20 id[i] = make([]int, n)21 }22 size := []int{0}23 var dfs func(int, int)24 dfs = func(i, j int) {25 id[i][j] = len(size) - 126 size[len(size)-1]++27 for _, d := range dir4 {28 x, y := i+d.x, j+d.y29 if 0 <= x && x < n && 0 <= y && y < n && a[x][y] != 'X' && id[x][y] == 0 {30 dfs(x, y)31 }32 }33 }34 for i, row := range a {35 for j, v := range row {36 if v == 'X' || id[i][j] > 0 {37 continue38 }39 size = append(size, 0)40 dfs(i, j)41 }42 }43 44 vis := make([]int, len(size))45 for top := range n - k + 1 {46 for r := range n {47 for _, row := range id[top : top+k] {48 size[row[r]]--49 }50 51 l := r + 1 - k52 if l < 0 {53 continue54 }55 56 s := 057 ts++58 for i := max(top-1, 0); i <= min(top+k, n-1); i++ {59 j, step, c := l, 1, k60 if i != top-1 && i != top+k {61 j, step, c = l-1, k+1, 262 }63 for range c {64 if 0 <= j && j < n {65 p := id[i][j]66 if p > 0 && vis[p] != ts {67 vis[p] = ts68 s += size[p]69 }70 }71 j += step72 }73 }74 ans = max(ans, s)75 76 for _, row := range id[top : top+k] {77 size[row[l]]++78 }79 }80 81 for l := n - k + 1; l < n; l++ {82 for _, row := range id[top : top+k] {83 size[row[l]]++84 }85 }86 }87 Fprint(out, ans+k*k)88}89 9091