Problem solution · Go

Codeforces 525D — Arthur and Walls

Codeforces 525D — Arthur and Walls: a Go solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Depth-first search
Source
EndlessCheng Codeforces Go
Length
57 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Codeforces 525D — Arthur and Walls, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 57 lines of Go from the credited upstream file 525D.go.
  • The implementation visibly relies on sequence storage, cached states.
  • 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.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 525D — Arthur and Walls · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io"	"runtime/debug") // https://github.com/EndlessChengfunc cf525D(in io.Reader, _w io.Writer) {	debug.SetMemoryLimit(500 << 20)	out := bufio.NewWriter(_w)	defer out.Flush()	var n, m uint16	Fscan(in, &n, &m)	g := make([][]byte, n+2)	g[0] = make([]byte, m+2)	for i := uint16(1); i <= n; i++ {		var s []byte		Fscan(in, &s)		g[i] = make([]byte, m+2)		copy(g[i][1:], s)	}	g[n+1] = make([]byte, m+2) 	var dfs func(uint16, uint16)	dfs = func(x, y uint16) {		if g[x][y] == '.' ||			!(g[x-1][y-1] == '.' && g[x-1][y] == '.' && g[x][y-1] == '.' ||				g[x-1][y+1] == '.' && g[x-1][y] == '.' && g[x][y+1] == '.' ||				g[x+1][y-1] == '.' && g[x+1][y] == '.' && g[x][y-1] == '.' ||				g[x+1][y+1] == '.' && g[x+1][y] == '.' && g[x][y+1] == '.') {			return		}		g[x][y] = '.'		for i := max(x-1, 1); i <= min(x+1, n); i++ {			for j := max(y-1, 1); j <= min(y+1, m); j++ {				if i != x || j != y {					dfs(i, j)				}			}		}	}	for i := uint16(1); i <= n; i++ {		for j := uint16(1); j <= m; j++ {			dfs(i, j)		}	} 	for _, row := range g[1 : n+1] {		Fprintf(out, "%s\n", row[1:m+1])	}} //func main() { cf525D(bufio.NewReader(os.Stdin), os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗