UVA之Fill the Square
Problem A
Fill the Square
Input: Standard Input
Output: Standard Output
In this problem, you have to draw a square using uppercase English Alphabets.
To be more precise, you will be given a square grid with some empty blocks and others already filled for you with some letters to make your task easier. You have to insert characters in every empty cell so that the whole grid is filled with alphabets. In doing so you have to meet the following rules:
- Make sure no adjacent cells contain the same letter; two cells are adjacent if they share a common edge.
- There could be many ways to fill the grid. You have to ensure you make the lexicographically smallest one. Here, two grids are checked in row major order when comparing lexicographically.
Input
The first line of input will contain an integer that will determine the number of test cases. Each case starts with an integer n( n<=10 ), that represents the dimension of the grid. The next n lines will contain n characters
each. Every cell of the grid is either a ‘.’ or a letter from [A, Z]. Here a ‘.’ Represents an empty cell.
Output For each case, first output Case #: ( # replaced by case number ) and in the next n lines output the input matrix with the empty cells filled heeding the rules above.
Sample Input Output for Sample Input
2 3 ... ... ... 3 ... A.. ... |
Case 1: ABA BAB ABA Case 2: BAB ABA BAB |
Problemsetter: Sohel Hafiz
【分析】
根據字典序的定義,我們可以從上到下,從左到右一位一位的求,先求滿足第一個元素最小,再求滿足第二個元素最小,
以此類推。本題中,我們隻需從左到右,從上到下依次給所有的空格填上最小可能的字母即可。
在填寫某個空格時,從‘A’到'Z',要跟這個空格的上麵,下麵,左邊,右邊的元素分別比較,找到一個字母。
【代碼】
/********************************* * 日期:2014-04-10 * 作者:SJF0115 * 題號: Fill the Square * 來源:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=27&page=show_problem&problem=2515 * 結果:AC * 來源:UVA * 總結: **********************************/ #include <iostream> #include <stdio.h> using namespace std; #define N 10 + 1 char matrix[N][N]; void FillTheSquare(int n){ if(matrix == NULL || n <= 0){ return; } int i,j; for(i = 0;i < n;i++){ for(j = 0;j < n;j++){ //.代表需要填寫的地方 if(matrix[i][j] == '.'){ //試著從A-E開始填寫是否成功 for(char c = 'A';c <= 'Z';c++){ bool ok = true; //上麵元素 if(i > 0 && matrix[i-1][j] == c){ ok = false; } //下麵元素 if(i < n-1 && matrix[i+1][j] == c){ ok = false; } //左邊元素 if(j > 0 && matrix[i][j-1] == c){ ok = false; } //右邊元素 if(j < n-1 && matrix[i][j+1] == c){ ok = false; } //該元素與周邊元素沒有衝突,填寫元素,停止嚐試 if(ok){ matrix[i][j] = c; break; } }//for }//if }//for }//for } int main(){ int T,i,j,k,n; while(scanf("%d",&T) != EOF){ for(k = 1;k <= T;k++){ scanf("%d",&n); for(i = 0;i < n;i++){ scanf("%s",matrix[i]); } //FillTheSquare FillTheSquare(n); //輸出 printf("Case %d:\n",k); for(i = 0;i < n;i++){ printf("%s\n",matrix[i]); } } } return 0; }
最後更新:2017-04-03 12:56:09