Go: package main

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

var sc = bufio.NewScanner(os.Stdin)

/**************  Cell  *****************/
type Cell struct {
    item interface{}
    next *Cell
    prev *Cell
}

func NewCell(x interface{}, ne *Cell, pr *Cell) *Cell {
    newCp := new(Cell)
    newCp.item = x
    newCp.next = ne
    newCp.prev = pr
    return newCp
}
/************  End Cell  ***************/

/**************  Queue  ****************/
type Queue struct {
    size int
    front *Cell
    rear *Cell
}

func NewQueue() *Queue {
    return new(Queue)
}

func (q *Queue) Push(x interface{}) {
    newNode := NewCell(x, nil, nil)
    if q.size == 0 {
        q.front = newNode
        q.rear = newNode
    } else {
        newNode.prev = q.rear
        q.rear.next = newNode
        q.rear = newNode
    }
    q.size++
}

func (q *Queue) PopLeft() interface{} {
    if q.size == 0 {
        return nil
    } else {
        x := q.front.item
        if q.size == 1 {
            q.front = nil
            q.rear = nil
        } else {
            q.front = q.front.next
            q.front.prev = nil
        }
        q.size--
        return x
    }
}

func (q *Queue) IsEmpty() bool {
    return q.size == 0
}

func (q *Queue) Length() int {
    return q.size
}

type State struct {
    color string
    cnt int
}

func main() {
    for {
        sc.Scan()
        init := sc.Text()
        if init == "0" {
            break
        }
        bfs(init)
    }
}

func bfs(init string) {
    dic := make(map[string]int)
    que := NewQueue()
    que.Push(State{init, 0})
    length := len(init)
    isSolved := false
    for !que.IsEmpty() {
        state := que.PopLeft().(State)
        _, ok := dic[state.color]
        if ok {
            continue
        } else {
            dic[state.color] = state.cnt
        }

        if isSingleColor(state.color) {
            fmt.Println(state.cnt)
            isSolved = true
            break
        }

        for i := 0;i < length - 1; i++ {
            color1, color2 := string(state.color[i]), string(state.color[i + 1])
            if color1 != color2 {
                color3 := other(color1, color2)
                if i <= length - 2 {
                    que.Push(State{state.color[:i] + color3 + state.color[i + 2:], state.cnt + 1})
                } else {
                    que.Push(State{state.color[:i] + color3, state.cnt + 1})
                }
            }
        }
    }
    if !isSolved {
        fmt.Println("NA")
    }
}

func other(color1, color2 string) string {
    if color1 == "r" {
        if color2 == "g" {
            return "bb"
        } else if color2 == "b" {
            return "gg"
        }
    } else if color1 == "g" {
        if color2 == "r" {
            return "bb"
        } else if color2 == "b" {
            return "rr"
        }
    } else if color1 == "b" {
        if color2 == "r" {
            return "gg"
        } else if color2 == "g" {
            return "rr"
        }
    }
    return ""
}

func isSingleColor(color string) bool {
    for _, c := range color {
        if string(c) != string(color[0]) {
            return false
        }
    }
    return true
}

C++: #include <iostream>
#include <queue>
#include <string>
#include <utility>
#include <set>
using namespace std;
typedef pair<string,int> P;
int main() {
	string str;
	while(cin>>str,str!="0") {
		queue<P> Q;
		Q.push(P(str,0));
		set<string> S;
		S.insert(str);
		while(!Q.empty()) {
			P p=Q.front(); Q.pop();
			bool Flag=true;
			for(int i=0;i<p.first.size()-1;i++) {
				if(p.first[i]!=p.first[i+1]) {Flag=false;break;}
			}
			if(Flag) {printf("%d\n",p.second); break;}
			for(int i=0;i<p.first.size()-1;i++) {
				string tmp=p.first;
				if((p.first[i]=='r' && p.first[i+1]=='g') || (p.first[i+1]=='r' && p.first[i]=='g')) {
					tmp[i]=tmp[i+1]='b';
				}else if((p.first[i]=='r' && p.first[i+1]=='b') || (p.first[i+1]=='r' && p.first[i]=='b')) {
					tmp[i]=tmp[i+1]='g';
				}else if((p.first[i]=='b' && p.first[i+1]=='g') || (p.first[i+1]=='b' && p.first[i]=='g')) {
					tmp[i]=tmp[i+1]='r';
				}else continue;
				if(S.find(tmp)==S.end()) {
					S.insert(tmp);
					Q.push(P(tmp,p.second+1));
				}
			}
		}
	}
}

C++: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
typedef vector<ll> V;
typedef complex<double> Point;
#define PI acos(-1.0)
#define EPS 1e-10
const ll INF = 1e16;
const ll MOD = 1e9 + 7;
#define FOR(i, a, b) for(int i=(a);i<(b);i++)
#define rep(i,N) FOR(i, 0, N)
#define ALL(s) (s).begin(), (s).end()
#define EQ(a, b) (abs((a) - (b)) < EPS)
#define EQV(a, b) (EQ((a).reeal(), (b).real) && EQ((a).imag(), (b).imag()))
#define NIL -1

ll g;
ll w;
ll d[100000];
char table[] = {'r','g','b'};

string myitos(ll num){
    string res = "";
    rep(i,w){
        res += table[num % 3];
        num /= 3;
    }
    reverse(ALL(res));
    return res;
}

ll mystoi(string s){
    ll res = 0;
    rep(i,s.size()){
        res *= 3;
        if(s[i] == 'g')res++;
        else if(s[i] == 'b')res += 2;
    }
    return res;
}

void dijkstra(ll start){
    fill(d,d+100000,INF);
    d[start] = 0;

    priority_queue<P,vector<P>,greater<P>> que;
    que.push(P(0,start));

    while(!que.empty()){
        P p = que.top();
        que.pop();
        ll v = p.second;
        ll cost = p.first;
        if(d[v] < cost)continue;
        // d[v] = cost;
        if(v == 0 || v == g || v == 2*g)continue;

        string now = myitos(v);

        rep(i,now.size() - 1){
            char c1 = now[i];
            char c2 = now[i+1];
            string t = now;
            if((c1 == 'r' && c2 == 'g') || (c1 == 'g' && c2 == 'r')){
                t[i] = 'b';
                t[i+1] = 'b';
            }
            if((c1 == 'g' && c2 == 'b') || (c1 == 'b' && c2 == 'g')){
                t[i] = 'r';
                t[i+1] = 'r';
            }
            if((c1 == 'b' && c2 == 'r') || (c1 == 'r' && c2 == 'b')){
                t[i] = 'g';
                t[i+1] = 'g';
            }
            ll to = mystoi(t);
            // cout << t << endl;
            if(d[to] > cost+1){
                d[to] = cost + 1;
                que.push(P(cost+1,to));
            }
        }

    }
}

string s;

int main(){
    while(cin >> s && s != "0"){
        int start = 0;
        w = s.size();
        g = 0;
        rep(i,s.size()){
            g *= 3;
            g++;
            int num = 0;
            if(s[i] == 'g')num++;
            if(s[i] == 'b')num += 2;
            start = 3*start + num;
        }
        // string t = myitos(start);
        // cout << t << endl;
        // cout << mystoi(t) << endl;
        // continue;
        dijkstra(start);
        ll ans = min(d[0],min(d[g],d[2*g]));
        if(ans == INF)cout << "NA" << endl;
        else cout << ans << endl;
    }
}

C++: #include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;

char dir[]{ 'r','g','b' };
int main() {
	string s;
	while (cin >> s, s != "0") {
		queue<string>que;
		unordered_map<string, int>mp;
		que.push(s);
		mp[s] = 1;
		while (!que.empty()) {
			string u = que.front(); que.pop();
			int r, g;
			if ((r = count(u.begin(), u.end(), 'r')) == u.size() ||
				(r == 0 && (g = count(u.begin(), u.end(), 'g')) == u.size()) ||
				(r == 0 && g == 0)) {
				printf("%d\n", mp[u] - 1);
				goto goal;
			}
			rep(i, u.size() - 1) {
				if (u[i] != u[i + 1]) {
					string v = u;
					v[i] = v[i + 1] = dir[3 - (find(dir, dir + 3, u[i]) - dir) - (find(dir, dir + 3, u[i + 1]) - dir)];
					if (!mp[v]) {
						mp[v] = mp[u] + 1;
						que.push(v);
					}
				}
			}
		}
		puts("NA");
	goal:;
	}
}