Go: package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

func configure(scanner *bufio.Scanner) {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1000005), 1000005)
}
func getNextString(scanner *bufio.Scanner) string {
	scanned := scanner.Scan()
	if !scanned {
		panic("scan failed")
	}
	return scanner.Text()
}
func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}
func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}
func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}
func main() {
	fp := os.Stdin
	wfp := os.Stdout
	extra := 0
	if os.Getenv("I") == "IronMan" {
		fp, _ = os.Open(os.Getenv("END_GAME"))
		extra = 100
	}
	scanner := bufio.NewScanner(fp)
	configure(scanner)
	writer := bufio.NewWriter(wfp)
	defer func() {
		r := recover()
		if r != nil {
			fmt.Fprintln(writer, r)
		}
		writer.Flush()
	}()
	solve(scanner, writer)
	for i := 0; i < extra; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
}
func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	n := getNextInt(scanner)
	s := getNextString(scanner)
	cc := makeGrid(9, 9)
	for i := 0; i < n-1; i++ {
		cc[s[i]-'0'-1][s[i+1]-'0'-1]++
	}
	p := make(permutation, 9)
	ans := make([]int, 9)
	p.dfs(0, 9, 0, ans, cc)
	for i := 0; i < 9; i++ {
		fmt.Fprint(writer, ans[i]+1)
		if i%3 == 2 {
			fmt.Fprintln(writer, "")
		}
	}
}
func makeGrid(h, w int) [][]int {
	index := make([][]int, h, h)
	data := make([]int, h*w, h*w)
	for i := 0; i < h; i++ {
		index[i] = data[i*w : (i+1)*w]
	}
	return index
}

var min int = math.MaxInt32

type permutation []int

func (p permutation) dfs(i, n int, used uint32, ans []int, cc [][]int) {
	if i == n {
		sum := getsum(p, cc)
		if min > sum {
			for i := 0; i < 9; i++ {
				ans[i] = p[i]
			}
			min = sum
		}
		return
	}
	for b := 0; b < 9; b++ {
		if used&(1<<uint(b)) != 0 {
			continue
		}
		p[i] = b
		p.dfs(i+1, n, used|(1<<uint(b)), ans, cc)
	}
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}
func getsum(p permutation, cc [][]int) int {
	sum := 0
	for i := 0; i < 9; i++ {
		for j := 0; j < 9; j++ {
			if i == j {
				continue
			}
			sum += (abs(i/3-j/3) + abs(i%3-j%3)) * cc[p[i]][p[j]]
		}
	}
	return sum
}

C++: #include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const static int INFTY = (1 << 30);
int nums[10][10];
int xs[10], ys[10];
map<int, pair<int, int> > dist;
char a[100001];

int main()
{
    int N, curr, next;
    int test[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int finalNum[10];
    scanf("%d", &N);
    scanf("%s", a);
    memset(nums, 0, sizeof (nums));
    curr = int(a[0] - '0');
    for (int i = 1; i < N; i++) {
        next = int(a[i] - '0');
        nums[curr][next]++;
        curr = next;
    }
    int global_min = INFTY;
    do {
        curr = 0;
        int idx = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) xs[test[idx]] = i, ys[test[idx++]] = j;
        }

        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= 9; j++) {
                if (nums[i][j]) curr += nums[i][j] * (abs(xs[i] - xs[j]) + abs(ys[i] - ys[j]));
            }
        }
        if (curr < global_min) {
            for (int i = 0; i < 9; i++) finalNum[i] = test[i];
            global_min = curr;
        }

    } while (next_permutation(test, test+9));

    int idx = 0;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) printf("%d", finalNum[idx++]);
        printf("\n");
    }

    return 0;
}

C++: #include <iostream>
#include <fstream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <array>
#include <bitset>
using namespace std;

#define REP(i,n) for(int i=0; i<n; ++i)
#define FOR(i,a,b) for(int i=a; i<=b; ++i)
#define FORR(i,a,b) for (int i=a; i>=b; --i)
#define ALL(c) (c).begin(), (c).end()

typedef long long ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef vector<VI> VVI;
typedef vector<VL> VVL;
typedef pair<int,int> P;
typedef pair<ll,ll> PL;

int in() { int x; scanf("%d", &x); return x; }
ll lin() { ll x; scanf("%lld", &x); return x; }

int main() {
    int n;
    string s;
    cin >> n >> s;
    int m = 9;
    VVI c(m, VI(m));
    REP(i,n-1){
        c[s[i]-'1'][s[i+1]-'1']++;
    }
    VI ans(m);
    int mi = 1e8;
    VI p(m);
    REP(i,m) p[i] = i;
    do{
        int tmp = 0;
        REP(i,m) REP(j,m){
            int d = abs(i / 3 - j / 3) + abs((i % 3) - (j % 3));
            tmp += d * c[p[i]][p[j]];
        }
        if (tmp < mi || (tmp == mi && p < ans)){
            mi = tmp;
            ans = p;
        }
    }while(next_permutation(ALL(p)));
    REP(i,m){
        cout << ans[i] + 1;
        if (i % 3 == 2) cout << endl;
    }
    return 0;
}

C++: #include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <typeinfo>
#include <numeric>
#include <functional>
#include <unordered_map>
#include <bitset>
#include <stack>


using namespace std;
using ll = long long;
using ull = unsigned long long;

const ll INF = 1e16;
const ll MOD = 1e9 + 7;

#define REP(i, n) for(ll i = 0; i < n; i++)






int main() {
    ll n;
    cin >> n;
    string s;
    cin >> s;
    vector<vector<ll>> cost(9, vector<ll>(9));
    REP(i, n - 1){
        ll a = s[i] - '0', b = s[i + 1] - '0';
        a--; b--;
        cost[a][b]++;
        cost[b][a]++;
    }
    vector<ll> ans;
    ll max_cost = INF;
    vector<ll> r = {0, 1, 2, 3, 4, 5, 6, 7, 8};
    do{
        vector<pair<ll ,ll>> p(9);
        REP(i, 9){
            p[r[i]] = {i / 3, i % 3};
        }
        ll sum = 0;
        REP(i, 9){
            REP(j, 9){
                if(i >= j || cost[i][j] == 0) continue;
                sum += (abs(p[j].first - p[i].first) + abs(p[j].second - p[i].second)) * cost[i][j];
            }
        }
        if(max_cost > sum){
            max_cost = sum;
            ans = r;
        }
    }while(next_permutation(r.begin(), r.end()));
    REP(i, 3){
        REP(j, 3){
            cout << ans[3 * i + j] + 1;
        }
        cout << endl;
    }
}

C++: #include<bits/stdc++.h>
using namespace std;

int c[9][9];
int x[9], y[9];
int main() {
    int n; cin >> n;
    string s; cin >> s;
    for (int i = 0; i < n - 1; ++i) {
        ++c[s[i] - '1'][s[i + 1] - '1'];
    }
    for (int i = 0; i < 9; ++i) for (int j = 0; j < 9; ++j) {
        // cerr << i << ' ' << j << ' ' << c[i][j] << '\t';
    }
    array<int, 9> idx, res;
    iota(begin(idx), end(idx), 0);
    int mn = 1e9;
    do {
        int curr = 0;
        for (int i = 0; i < 9; ++i) {
            x[idx[i]] = i / 3;
            y[idx[i]] = i % 3;
        }
        for (int i = 0; i < 9; ++i) for (int j = 0; j < 9; ++j) {
            curr += c[idx[i]][idx[j]] * (abs(x[idx[i]] - x[idx[j]]) + abs(y[idx[i]] - y[idx[j]]));
        }
        // cerr << curr << endl;
        if (curr < mn) {
            // cerr << curr << endl;
            mn = curr;
            res = idx;
        }
    } while (next_permutation(begin(idx), end(idx)));
    for (int i = 0; i < 9; i += 3) {
        cout << res[i] + 1 << res[i + 1] + 1 << res[i + 2] + 1 << "\n";
    }
    return 0;
}