www.acmicpc.net/problem/7562

 

7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수 ��

www.acmicpc.net

 

문제풀이

  • 이동 dx, dy를 잘 체크해준다.
  • 이동 할 때마다 체크 및 +1 씩 해준다.
  • 도착 지점이면 바로 break;로 나온다.

c++

#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
#include <vector>
/*
8
0 0
7 0 */

using namespace std;
int k, sa, sb, ea, eb;
int visit[1000][1000];
const int dx[] = { 2, 1, -1, -2, -2, -1, 1, 2 };
const int dy[] = { 1, 2, 2, 1, -1, -2, -2, -1 };
 

int ans;

struct Point
{
	int x;
	int y;
	int num;
};
queue <Point> q;
vector<int> answer;

void input()
{
	cin >> k;
	cin >> sa >> sb;
	cin >> ea >> eb; 
}
int solve()
{
	visit[sa][sb] = 1;
	q.push({ sa, sb, 0 });
	while (!q.empty())
	{
		Point pp = q.front();
		int x = pp.x;
		int y = pp.y;
		int nn = pp.num;
		q.pop();
	

		for (int w = 0; w< 8; w++)
		{
			int nx = x + dx[w];
			int ny = y + dy[w];
			int nnn = nn + 1;
			if (nx == ea && ny == eb)
			{
				return nnn;
			}
			if (nx >= k || ny >= k || nx < 0 || ny < 0)
			{
				continue;
			}
			if (visit[nx][ny] == 1)
				continue;
			if (visit[nx][ny] == 0)
			{
				visit[nx][ny] = 1;
				q.push({ nx, ny, nnn  });
			}


		}
	}
	return 0;
}
void Init()
{

	queue <Point> q;
	memset(visit, 0, sizeof(visit));
	ans = 0; 
 
}
int main()
{
	int t; cin >> t;
	for (int i = 0; i < t; i++)
	{
		input();
		Init();
		int anss = solve();
		cout << anss << endl;
	}


	return 0;
}

 

 

Java

package Z_J_Code;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.io.*;
class Location12 {
	int x;
	int y;
	int level;
	public Location12 (int x, int y, int level) {
		this.x= x;
		this.y=y;
		this.level= level;
	}
}
public class Main3 {
	

	static int L;//체스판 크기
	//static int board[][];
	static int visited[][];
	//static Stack<Location> stk= new Stack<Location>();
	static Queue<Location12> que = new LinkedList<Location12>();
	static int dir_x [] = {-1, -2,-2, -1, 1, 2, 2, 1};
	static int dir_y []= {-2, -1,1, 2, 2, 1,-1, -2};
	static int count=0;
	
	
	static int search (int x, int y, int endX, int endY) {
		//stk.push(new Location(x,y)); 
		que.add(new Location12(x,y,0));
		while (!que.isEmpty()) {
			Location12 current =que.poll();
			//if (current.x==endX && current.y==endY) return;
			//count++;
			//System.out.println("curent:"+ current.x+ ","+ current.y+ ","+ current.level);
			for (int i=0; i<dir_x.length; i++) {
				int nextX= current.x+dir_x[i];
				int nextY= current.y+dir_y[i];
				int level= current.level+1;
				if (nextX==endX && nextY==endY) {
					//System.out.println(nextX+", "+ nextY);
					return level;
				}
				if (nextX>=0 && nextX<L && nextY>=0 && nextY<L && visited[nextX][nextY]==0) {
					//System.out.println(nextX+", "+ nextY+ ","+ level);
					visited[nextX][nextY]=1;
					que.add(new Location12 (nextX, nextY,level));
					//count++;
					
				}
			}
		}
		return 0;
	}
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		int tc =Integer.parseInt(br.readLine()); //테케 갯수
		for (int i=0; i<tc; i++) {
			que.clear();
			count=0;
			L= Integer.parseInt(br.readLine()); //체스판 크기
			
			//board = new int [L][L];
			visited = new int [L][L];
			for (int row[]: visited) {
				Arrays.fill(row,  0);
			} //초기화시킴
			String input= br.readLine();
			StringTokenizer st= new StringTokenizer(input);
			int startX= Integer.parseInt(st.nextToken()); 
			int startY= Integer.parseInt(st.nextToken());
			input = br.readLine();
			st= new StringTokenizer(input);
			
			int endX= Integer.parseInt(st.nextToken()); 
			int endY= Integer.parseInt(st.nextToken()); 
			
			if (startX==endX && startY==endY) System.out.println(0);
			else {
			visited[startX][startY]=1;
			System.out.println(search(startX, startY, endX, endY));
			}
			//System.out.println(count);
		}
	}

}

www.acmicpc.net/problem/2644

 

2644번: 촌수계산

사람들은 1, 2, 3, …, n (1≤n≤100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어진�

www.acmicpc.net

 

문제풀이

(7) (3)
2 1
1  
  • 노드 짜는 문제...!
  • 노드 (부모, 자식) 중요 
    • 조상, 자식 개념으로 생각하는게 맞을듯...
    • 출발 부터 조상은 여러명이 될 수있음.
  • 각각 서로 같은 조상을 만났을 때
    • 직속 : 본인(person1)과 목적지(person2)가 서로 할아버지->아버지->나 이런 관계 일때 ex) 7-2 관계
    • 직속으로 만났을 땐 해당 인덱스 +1 해준다. 
    • 직속이 아닐 경우 각각의 인덱스에서 +2 해준다. +2 란 가는 경로를 다 더해주는 느낌이다.
  • 입력 받아오는 것 노드 연결 까지 입력 코테에서는 가장 좋은 문제

C++

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
struct aaa
{
	int p;
	vector<int> v;
};
aaa ar[10001];
int num1,num2;
int ans;
int cnt;

void input()
{
	int numSize;
	cin >> numSize;
	for(int i =0 ; i < numSize; i++)
	{
		int a, b;
		cin >> a >> b; //1,2 
		ar[a].v.push_back(b);
		ar[b].p = a;
	}

}

void dfs(int n)
{
	int temp;
	temp = ar[n].p;
	if (n == ans || ans ==-1 ||temp ==0)
	{
		return;
	}
	cnt++;
	
	
	if (temp != 0)
		dfs(temp);
	else
		return;
}
void solve()
{
	vector<int> vv[2];
	//ROOT 이면..
	if (ar[num1].p == 0 && ar[num1].v.size() == 0)
		return;
	if (ar[num2].p == 0 && ar[num2].v.size() == 0)
		return;
	vv[0].push_back(num1);
	int x =num1;
	while (1)
	{
		if (ar[x].p == 0) //즉 부모가 없으면 
		{
			//vv[0].push_back(0);//부모삽입
			break;
		}
		vv[0].push_back(ar[x].p);//부모삽입
		x = ar[x].p;  // x를 부모로 바꿈 그 부모를 찾기위해  따라서 v[1]에는 부모들이 쌓임 
	}
	vv[1].push_back(num2);
	int y =num2 ;
	while (1)
	{
		if (ar[y].p == 0)
		{
			break;
		}
		vv[1].push_back(ar[y].p); //두번째숫자의 부모들 넣음
		y = ar[y].p; //부모 체인지  맨끝까지 올라감 
		//즉 3,7은 각자의 맨끝인 1까지 삽입 
	}
	
	
	

	for (int i = 0; i < vv[0].size(); i++)
	{
		
		bool flag = false;
		int res;
		for (int j = 0; j< vv[1].size(); j++)
		{
			if (vv[0][i] == vv[1][j])
			{
				res = vv[0][i];
				flag = true;
				break;
			}
			/*else 
			{
				ans = -1; //조상이 같지 않음! 남남
			}*/
			
		}

	//	sort(vv[0].rbegin(), vv[0].rend());
//		sort(vv[1].rbegin(), vv[1].rend());

		if (flag == true) //조상을 찾았다면!
		{
			//추가
			for (int w = 0; w < vv[0].size(); w++)
			{
				cnt++;
				if (vv[0][w] == res)
				{
					break;
				} 
			}
			for (int w = 0; w < vv[1].size(); w++)
			{
				cnt++;
				if (vv[1][w] == res)
				{
					break;
				}
			}
			cnt -= 2;
			break;
		}
	}
 
}

int main()
{
	int tm;
	cin >> tm;
	cin >> num1 >> num2;
	input();
	solve();
	if (cnt == 0)
	{
		cnt = -1;
	}
	cout << cnt << endl;
	return 0;
}

 

Java

package Z_ShinHanCard_Prepare;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class Node_Family
{
	int parent;
	ArrayList<Integer> child;
	int level;
	public Node_Family(int parent, ArrayList<Integer> child, int level) {
		super();
		this.parent = parent;
		this.child = child;
		this.level = level;
	}
	 
}

public class D2백준2644_촌수계산_DFSBFS_노드 {
	static Node_Family family[] =new Node_Family[101];
	static int answer ;
	static void solve(int person, int person2)
	{
		int x = person;  //7 
		ArrayList<Integer> [] arr= new ArrayList[2];
		Queue<Integer>que= new LinkedList<Integer>();
		for (int i=0; i<2;i++) 
		{
			arr[i]= new ArrayList<Integer>();
		}
		//node1의 부모탐색 즉 7의 부모탐색 
		while(true)
		{
			//부모가 더이상없다면 끝내 처음에 0으로 생성함.
			if(family[x].parent==0)
				break;
			//아니면 arr[0]리스트에 부모들을 다 더해준다. 아버지+할아버지
			arr[0].add(family[x].parent);
			x= family[x].parent; 
		}
		//숫자 3에 조상 다 구하기
		x= person2;
		while(true)
		{
			if(family[x].parent==0)
				break;
			arr[1].add(family[x].parent);
			x= family[x].parent;
		}
		//첫놈의 조상 중에 둘째 놈이 있다면 ?
		if(arr[0].contains(person2))
		{
			// [0][0] 있다면 1촌 [0][1]에 있다면 2촌
			answer= arr[0].indexOf(person2)+1;
		}else if (arr[1].contains(person))
			answer =arr[1].indexOf(person)+1;
		else
		{
			boolean flag = false;
			for(int i = 0 ; i<arr[0].size();i++)
			{	for(int j = 0 ; j < arr[1].size(); j++)
				{
					if(arr[0].get(i)==arr[1].get(j) )
					{
						answer = i+j +2;
						flag=true;
						break;
					}
				}
				if(flag)
					break;
			}
			
			if(!flag)
			{
				answer = -1; 
			}
		}
		
	}
	
	
	public static void main(String[] args) throws Exception 
	{
		/*
		 *  9 //전체사람수 9명 
			7 3 //7과 3은?
			7   //관계 7
			1 2
			1 3
			2 7
			2 8
			2 9
			4 5
			4 6
		 * */
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		int m= Integer.parseInt(br.readLine()); //총 인원 : 9
		String input= br.readLine(); //누구누구?  7,3 
		StringTokenizer st= new StringTokenizer(input);
		int person= Integer.parseInt(st.nextToken()); //7
		int person2= Integer.parseInt(st.nextToken());//3
		// TODO Auto-generated method stub
		int e= Integer.parseInt(br.readLine()); //7번 !
		for(int i = 0 ; i<family.length;i++)
		{
			family[i] =new Node_Family(0,new ArrayList<Integer>(), 0);
		}
		for(int i =0 ; i <e ; i++)
		{
			input =br.readLine();//1,2 -> 1,3 
			st= new StringTokenizer(input);
			int node1= Integer.parseInt(st.nextToken()); //1
			int node2=Integer.parseInt(st.nextToken()); //2
			//1의 자식 2라는 뜻 1의 자식이 여러명 일수 있으니 array리스트로 구현 C++ 이었으면 vector
			family[node1].child.add(node2);  
			family[node2].parent=node1;  //2의 부모는 1이라는 
		}
		
		solve(person,person2); // 7,3 목적지 
		System.out.println(answer);	
		

	}

}

 

'Algorithm' 카테고리의 다른 글

[백준 9012] 괄호 (Java)  (0) 2020.09.07
[백준 7562] 나이트의 이동 (C++, Java)  (0) 2020.09.07
[백준 2309] 일곱 난쟁이 (C++, Java)  (0) 2020.09.06
[백준 2178] 미로찾기 (C++, Java)  (0) 2020.09.06
[백준_1260] DFSBFS  (0) 2020.09.06

www.acmicpc.net/problem/2309

 

2309번: 일곱 난쟁이

아홉 개의 줄에 걸쳐 난쟁이들의 키가 주어진다. 주어지는 키는 100을 넘지 않는 자연수이며, 아홉 난쟁이의 키는 모두 다르며, 가능한 정답이 여러 가지인 경우에는 아무거나 출력한다.

www.acmicpc.net

 

문제풀이

  • dfs를 통해 9명 중 7명을 뽑는 Combination(조합)을 해주는 문제
  • 조합 코드 : 다시 for문으로 갈때 i=x부터 시작하는것이 중요! visit 중요 !
  • sum==100 이면 바로 탈출 dfs 진입 처음 if문에 flag 이용 !
	for(int i = x ; i<9 ; i++)
		{
			if(flag == true)
				break;
			if(vi[i]==false)
			{
				vi[i]=true; 
				//sum = sum + Nan[i];
				dfs(x+1,num+1,sum+Nan[i]);
				
				//sum = sum -Nan[i];
				vi[i]=false;	
			}			
		}

 

C++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool visit[9] = { false, };
int arrNuan[9] = { 0, };
bool flag = false;
vector<int> v;
void input()
{

	for (int i = 0; i < 9; i++)
	{
		int temp;
		cin >> temp;
		arrNuan[i] = temp;
	}
}
void dfs(int p,int cnt, int sum)
{	
	if (cnt == 7)
	{
		if (sum == 100)
		{
			flag = true;
			sort(v.begin(), v.end());
			for (auto i : v)
			{
				
				cout << i << endl;
			}
		}
		return;
	}

	for (int w = p; w < 9; w++)
	{
		if (!visit[w])
		{
			visit[w] = true;
			v.push_back(arrNuan[w]);
			dfs(w, cnt+1, sum + arrNuan[w]);
			if (flag) break;
			 

			v.pop_back();
			visit[w] = false;
		}

	}
}

int main()
{
	visit[9] = { false, };
	arrNuan[9] = { 0, };
	flag = false;
	for (int i = 0; i < v.size(); i++)
		v.pop_back();
	input();
	dfs(0,0,0);

	return 0;
}

 

Java

package Z_ShinHanCard_Prepare;
import java.util.*;
public class D2백준2309_일곱난쟁이_DFS {

	//9C7 뽑는 경우의 수 !!
	static int[] Nan =  new int[9];;
	static boolean[] vi = new boolean[9];;
	static ArrayList<Integer> arr =new ArrayList<Integer>();
	static boolean flag; 
	static void dfs(int x, int num,int sum)
	{
		
		if(num==7)
		{
			if(sum==100)
			{
				//arr = new ArrayList<Integer>();
				for(int i =0  ; i < 9 ; i++ )
				{
					if (vi[i]==true)
					{
						arr.add(i);
					 
					}
					flag=true;
				 
				}
			}
			return;
		}
		
		for(int i = x ; i<9 ; i++)
		{
			if(flag == true)
				break;
			if(vi[i]==false)
			{
				vi[i]=true; 
				//sum = sum + Nan[i];
				dfs(x+1,num+1,sum+Nan[i]);
				
				//sum = sum -Nan[i];
				vi[i]=false;	
			}			
		}
		
	}
	public static void main(String[] args) 
	{
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		
		for(int i =0 ; i < 9 ; i ++)
		{
			int temp = sc.nextInt();
			Nan[i] = temp;
		}
		
		dfs(0,0,0);
		
		ArrayList<Integer> answer = new ArrayList<Integer>();
		for(int x : arr)
		{
			answer.add(Nan[x]); 
		}
		Collections.sort(answer);
		
		for(int x : answer)
		{
			System.out.println(x);
		}
		
		
		
	}

}

www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

 

 

 

문제풀이

  • 입력 받는 부분 tip (String 으로 받아도 -'0' 해주면 int로 돌아온다.
		map = new int[R][C];
		visit= new boolean[R][C];
		for(int i =0 ; i <R ; i++)
		{
			String input1 = br.readLine();
			for(int j = 0 ; j < C ; j++ )
			{
				map[i][j] = input1.charAt(j) - '0'; 
			}
		}
  • BFS를 돌면서 이동 가능한 칸은 자기자신의 숫자+1 결국 (최단거리)

C++ 

#include <queue>
#include <iostream>
#include <algorithm>

using namespace std;


int ar[101][101];
int vi[101][101];
int dx[] = { 1, -1, 0, 0 };
int dy[] = { 0, 0, 1, -1 };
int n, m, ans = 1000000;

queue<pair<int, int>> q;




void input()
{
	cin >> n >> m;
	// nxm 짜리 
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			scanf("%1d", &ar[i][j]); //꿀팁
		}
	}
}

void bfs() {
	q.push({ 0, 0 });
	vi[0][0] = 1;
	ar[0][0] = 0;
	while (!q.empty())
	{
		int x = q.front().first;
		int y = q.front().second;
		q.pop();

		if (x == n - 1 && y == m - 1)
		{
			ans = vi[x][y];
			break;
		}


		for (int w = 0; w < 4; w++)
		{
			int nx = x + dx[w];
			int ny = y + dy[w];

			if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;

			if (vi[nx][ny] == 0 && ar[nx][ny] == 1)
			{
				
				vi[nx][ny] = vi[x][y] + 1;
				q.push({ nx, ny });
			}

		}

	}

}

void dfs(int x, int y, int su) {
	if (x == n - 1 && y == m - 1) {
		ans = min(su, ans);
		return;
	}

	for (int w = 0; w < 4; w++)
	{
		int nx = x + dx[w];
		int ny = y + dy[w];
		if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
		if (vi[nx][ny] == 0 && ar[nx][ny] == 1) 
		{
			
			vi[nx][ny] = vi[x][y] + 1;
			dfs(nx, ny, vi[nx][ny]);
			vi[nx][ny] = 0;
		}
	}
}

int main()
{
	input();
	bfs();
	cout << ans  << endl;
	return 0;
}

 

Java

package Z_ShinHanCard_Prepare;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class Box
{
	int x;
	int y;
	int z;
	public Box(int x, int y)
	{
		this.x = x;
		this.y = y;
		this.z = z;
	}
}
public class D2백준2178_미로탐색_DFSBFS 
{
	static int R,C,Z;
	static int[][] map;
	static boolean[][] visit;
	static int[] dx = { -1,1,0,0};
	static int[] dy = { 0,0,-1,1};
	
	static void bfs(int x, int y)
	{
		Queue<Box> q = new LinkedList<Box>(); 
		q.add(new Box(x,y));
		while(!q.isEmpty())
		{
			Box box = q.poll();
			for(int w=  0 ; w< 4 ; w++)
			{
				int nx = box.x + dx[w];
				int ny = box.y +dy[w];
				if(nx<0 || nx>=R || ny <0 || ny >=C)
					continue;
				if(visit[nx][ny])
					continue;
				if(map[nx][ny] == 0)
					continue;
				q.add(new Box(nx,ny));
				visit[nx][ny] = true;
				box.z = map[nx][ny]+1;
				map[nx][ny] = map[box.x][box.y] + 1;
						
			}
			
			
		}
	}
	public static void main(String[] args) throws IOException 
	{
		
		// TODO Auto-generated method stub
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		String input = br.readLine();
		StringTokenizer st= new StringTokenizer(input);
		R= Integer.parseInt(st.nextToken()); //4
		C= Integer.parseInt(st.nextToken()); //6
		
		map = new int[R][C];
		visit= new boolean[R][C];
		for(int i =0 ; i <R ; i++)
		{
			String input1 = br.readLine();
			for(int j = 0 ; j < C ; j++ )
			{
				map[i][j] = input1.charAt(j) - '0'; 
			}
		}
		
		visit[0][0] =true;
		bfs(0,0);
		System.out.println(map[R-1][C-1]);
		

	}

}

 

www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

 

문제풀이

  • 노드연결이 중요함.
  • dfs/bfs 이해
  • check 배열 중요 !
1 2 3 4
2 1 1 1
3 4 4 2
4     3
       

 

DFS : 1->2->4->3

BFS : 1->2->3->4 //1에서 이미 다 Queue에 들어가면서 방문.

 

C++

 

 

Java

package Z_ShinHanCard_Prepare;

import java.util.*;

public class D2백준1260_DFSBFS {
	static int N, M, K;
	static boolean[] check;
	static ArrayList<Integer>[] arr;

	public static void dfs(int s) {
		if (check[s])
			return;
		check[s] = true;
		System.out.print(s + " ");
		for (int y : arr[s]) {
			if (check[y] == false) {
				dfs(y);
			}
		}
	}

	public static void bfs(int s) {
		Queue<Integer> q = new LinkedList<Integer>();
		q.offer(s);
		
		check[s] = true;
		while (!q.isEmpty()) {
			int x = q.poll();			
			System.out.print(x+" ");
			for (int w = 0; w < arr[x].size(); w++) 
			{
				int nx = arr[x].get(w);
				if (check[nx])
					continue; 
				q.add(nx);
				check[nx] = true; 
			}

		}

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		// TODO Auto-generated method stub
		N = sc.nextInt();
		M = sc.nextInt();
		K = sc.nextInt();
		arr = new ArrayList[N + 1];

		for (int i = 0; i <= N; i++) {
			arr[i] = new ArrayList<Integer>();
		}
		for (int i = 0; i < M; i++) {
			int u, v;
			u = sc.nextInt();
			v = sc.nextInt();
			arr[u].add(v);
			arr[v].add(u);
		}
		for (int i = 0; i < arr.length; i++) {
			Collections.sort(arr[i]);
		}
		check = new boolean[N + 1];
		dfs(K);
		check = new boolean[N + 1];
		System.out.println();
		bfs(K);

	}

}

 

www.acmicpc.net/problem/12871

 

12871번: 무한 문자열

첫째 줄에 s, 둘째 줄에 t가 주어진다. 두 문자열 s와 t의 길이는 50보다 작거나 같은 자연수이고, 알파벳 소문자로만 이루어져 있다. 

www.acmicpc.net

 

해결방법

  • ab <-> abab 일 경우
  • 포인터를 있다고 가정하여 문자열이 끝나면 다시 0으로 옮겨 주는 방법

코드

 

C++

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string s, t;
int che = 0;

void solve() {
	 
	if (s.size() > t.size()) swap(s, t); // swap 개꿀... 
	int a = 0; int b = 0;
	bool flag = false;
	int ct = 0;
	while (ct <= 500) {
		if (s[a] != t[b]) {
			che = 0;
			flag = true;
			break;
		}
		a++;
		b++;
		if (a == s.size()) a = 0;
		if (b == t.size()) b = 0;
		ct++;
	}

	if (!flag) che = 1;
}

int main() {
	cin >> s >> t;
	solve();
	cout << che << endl;
	return 0;
}

 

Java

 

import java.io.*;

public class Main {

	 static int che =0;
	public static void main(String[] args) throws Exception  {
		// TODO Auto-generated method stub

		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		String s = br.readLine();//ab
		String t = br.readLine();//abab
 
		if(s.length() > t.length())
		{
			String tmp;
			tmp = s;
			s = t;
			t = tmp;
		}
		
		int a=0;
		int b=0;
		boolean flag = false;
		int ct = 0;
		while(ct<=500)
		{
			if(s.charAt(a) != t.charAt(b))
			{
				che = 0;
				flag = true;
				break;
			}
			a++;
			b++;
			if(a==s.length())
				a=0;
			if(b==t.length())
				b=0;
			ct++;
		}
		
		if(!flag) che=1; 
		
		System.out.println(che);	
	}

}

 

'Algorithm' 카테고리의 다른 글

[백준 2178] 미로찾기 (C++, Java)  (0) 2020.09.06
[백준_1260] DFSBFS  (0) 2020.09.06
[백준2667] 단지번호 붙히기 (C++, Java)  (0) 2020.09.03
[백준 1987] 알파벳 (C++, Java)  (0) 2020.09.03
[백준 1697] 숨바꼭질 C++, Java  (0) 2020.09.03

www.acmicpc.net/problem/2667

 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. �

www.acmicpc.net

 

 

풀이방법

  • BFS로 순회하면서 visit처리해준다.
  • 단지가 끝나면 새로운 단지를 찾는다. 찾으면 총 단지수를 ++ 해준다
  • 새로운 단지 BFS하며 q에서 pop할때 마다 각 단지의 수 해주어 각 단지의 갯수를 구한다.
  • Java에서 Vector 대신 List를 써주며 sort 법이 조금 다르다.

C++

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

int ar[26][26];
int vi[26][26];
int dx[] = { 1, -1, 0, 0 };
int dy[] = { 0, 0, 1, -1 };
int n;
vector<int> v;
vector<int> ans;
int ct = 0; int ct2 = 0;

void input() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) scanf("%1d", &ar[i][j]);
	}
}

void bfs(int i, int j) {
	ct = 0;
	ct2++;
	queue<pair<int, int>> q;
	q.push({ i, j });
	vi[i][j] = 1;
	while (!q.empty()) 
	{
		int x = q.front().first;
		int y = q.front().second;
		q.pop();
		ct++;

		for (int w = 0; w < 4; w++) {
			int nx = x + dx[w];
			int ny = y + dy[w];
			if (nx < 0 || nx >= n || ny < 0 || ny >= n)
				continue;
			if (ar[nx][ny] != 0 && vi[nx][ny] == 0) 
			{
				vi[nx][ny] = 1;
				q.push({ nx, ny });
			}
		}
	}

	v.push_back(ct);
}

void solve() {
	for (int i = 0; i < n; i++) 
	{
		for (int j = 0; j < n; j++) 
		{
			if (ar[i][j] != 0 && vi[i][j] == 0) 
				bfs(i, j);
		}
	}
	ans.push_back(ct2);
	sort(v.begin(), v.end());
	for (int i = 0; i < v.size(); i++) ans.push_back(v[i]);
}

int main() {
	input();
	solve();
	for (int i = 0; i < ans.size(); i++) cout << ans[i] << endl;
	return 0;
}

 

Java

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*; 

class Node
{
	int x;
	int y;
	ArrayList<String> list;
	Node(int x, int y)
	{
		this.x = x;
		this.y = y;
		this.list =new ArrayList<String>();
	}
}

public class 백준2667_단지번호붙히기_DFSBFS1 
{
	ArrayList<ArrayList<String>> list4 = new ArrayList<ArrayList<String>>();
	static int house[][];
	static boolean[][] visited;
	static int N;
	static int dir_x[]= {-1,1,0,0};
	static int dir_y[]= {0,0,-1,1};
	
	static ArrayList<Integer> listall= new ArrayList<Integer>();
	static ArrayList<Integer> list= new ArrayList<Integer>();
	//static Stack<Node> stck= new Stack<Node> ();
	static int count=0;
	static int ct =0;
	static int ct2 =0;
	
	public static void bfs(int i, int j )
	{
		ct =0;
		ct2++;
		Queue <Node> q = new LinkedList<Node> ();
		q.add(new Node(i,j));
		while(!q.isEmpty())
		{
			Node p = q.poll(); 
			int x = p.x;
			int y = p.y;
			visited[x][y] =true;
			ct++;
			for(int w= 0 ; w <4 ; w++)
			{
				int nx = x + dir_x[w];
				int ny = y + dir_y[w];
				
				if (nx <0 || nx >=N || ny < 0 || ny >=N)
					continue;
				if(visited[nx][ny])
					continue;
				if(house[nx][ny] !=0)
				{
					q.add(new Node(nx,ny));
					visited[nx][ny] =true;	
				}
				
			}
					
		}
		
		list.add(ct);
	}
	
	
	public static void solve()
	{
		for (int i = 0; i < N; i++) 
		{
			for (int j = 0; j < N; j++) 
			{
				if (house[i][j] != 0 && visited[i][j] == false) 
					bfs(i, j);
			}
		}
		listall.add(ct2);
		Collections.sort(list);
		for(int i = 0 ; i<list.size();i++)
		{
			listall.add(list.get(i));
		}
	}
	
	public static void main(String[] args) throws IOException 
	{
		BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
		String input= br.readLine();
		N = Integer.parseInt(input);
		house = new int [N][N];
		visited = new boolean [N][N];
		//Arrays.fill(visited, false);
		for(int i = 0 ; i < N; i++)
		{
			input = br.readLine();
			for(int j =0 ; j < N ; j++)
			{
				int tempNum = input.charAt(j);
				house[i][j] = input.charAt(j) -'0'; 
			}
		}
		solve();
		
		//System.out.println(list.size());
		for (int i=0; i<listall.size(); i++)
		{
			System.out.println(listall.get(i));
		}
		// TODO Auto-generated method stub

	}

}

'Algorithm' 카테고리의 다른 글

[백준_1260] DFSBFS  (0) 2020.09.06
[백준 12871] 무한문자열 (C++, Java)  (0) 2020.09.03
[백준 1987] 알파벳 (C++, Java)  (0) 2020.09.03
[백준 1697] 숨바꼭질 C++, Java  (0) 2020.09.03
[프로그래머스] 폰켓몬 C++, Java  (0) 2020.09.03

www.acmicpc.net/problem/1987

 

1987번: 알파벳

세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한 칸으

www.acmicpc.net

 

 

문제해설

  • DFS 로 문제풀이 
  • DFS 로 순회하면서 다른 문자가 나타나면 Count++
  • 4 방향 다 돌고 같은 문자 만날시 나와주면서 Count--; 방문 취소 처리 재귀

 

SOL

C++

#include <iostream>
#include <queue>
#include <string>
#include <algorithm>

using namespace std;

bool visit[26];
int n, m;
char arr[25][25];
int dx[] = { -1, 0, 1, 0 };
int dy[] = { 0, -1, 0, 1 };
int answer = 0;
 
void dfs(int cnt, int ii, int jj)
{
	answer = max(answer, cnt);

	 
	for (int w = 0; w < 4; w++)
	{
		int nx = ii + dx[w];
		int ny = jj + dy[w];

		if (nx < 0 || ny < 0 || nx>=n || ny >=m )
		{
			continue;
		}
		if (visit[arr[ii][jj] - 'A'] == false)
		{  
			visit[arr[ii][jj] - 'A'] = true;
			dfs(cnt + 1, nx, ny);
			visit[arr[ii][jj] - 'A'] = false;

		}
	}

	 
}
void input()
{
	cin >> n >> m;

	for (int i = 0; i < n; i++)
	{
		string temp;
		cin >> temp;

		for (int j = 0; j < m; j++)
		{
			arr[i][j] = temp[j];
		}
	}
}
int main()
{
 
	input();
	dfs(0, 0, 0);
	cout << answer << endl;
	return 0;
}

 

Java

package Z_ShinHanCard_Prepare;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class 백준1987_알파벳_DFSBFS 
{
	static int R;
	static int C;
	static int dir_x[]= {-1,1,0,0};
	static int dir_y[]= {0,0,-1,1};
	static char map[][];
	static int visited[][];
	static String str= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	static int alpha[]= new int[str.length()];
	static int count=1;
	static int answer=1;
	public static void search (int x, int y) {
		char curr=map[x][y];
		
		
		alpha[str.indexOf(curr)]=1;
		for (int i=0; i<4; i++) {
			int next_x=x+dir_x[i];
			int next_y= y+dir_y[i];
			
			if (next_x<0 || next_x>=R ||next_y<0 || next_y>=C) continue;
			int temp= map[next_x][next_y];
			int temp2 = str.indexOf(temp);
			if (alpha[str.indexOf(temp)]==1) continue;
			count++;
			answer= Math.max(answer, count);
			search(next_x, next_y);
			
		}
		count--;
		alpha[str.indexOf(curr)]=0;
	}
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		String input= br.readLine();
		StringTokenizer st= new StringTokenizer(input);
		R= Integer.parseInt(st.nextToken());
		C= Integer.parseInt(st.nextToken());
		map= new char [R][C];
		visited= new int [R][C];
		Arrays.fill(alpha, 0);
		for (int arr[]: visited) {
			Arrays.fill(arr, 0);
		}
		
		for (int i=0; i<R; i++) {
			input= br.readLine();
			for (int j=0; j<C; j++) {
				map[i][j]= input.charAt(j);
			}
		}
		search(0,0);
		System.out.println(answer);
		
	}

}

+ Recent posts